导出的.jar当FileNotFoundException异常 [英] FileNotFoundException when exporting .jar

查看:319
本文介绍了导出的.jar当FileNotFoundException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的客户机/服务器应用程序,我需要把一些文件( .TXT .DOC 等。 )从客户机到服务器。当我在Eclipse中运行我的code它的工作原理,但是当我出口该Applet的签名的JAR没有。它抛出一个 FileNotFoundException异常。我试图保存文件中没有成功的几种方法。

In my client/server app I need to send some file (.txt, .doc, etc.) from the client to the server. When I run my code in Eclipse it works, but when I export the signed JAR of the Applet it doesn't. It throws a FileNotFoundException. I tried saving file in several ways without success.

public static boolean saveFile(File sourceFile) throws IOException {

    DirectoryChooserDialog dialog = new DirectoryChooserDialog();
    filePath = dialog.getDestinationFolder();
    if (filePath != null) {
        InputStream inputFile = ClassLoader.getSystemResourceAsStream(""+sourceFile);

        filePath += File.separator + sourceFile.getName();

        FileOutputStream outputFile = new FileOutputStream(filePath);

        int byteLetti = 0;
        while ((byteLetti = inputFile.read(buffer)) >= 0) {
            outputFile.write(buffer, 0, byteLetti);
            outputFile.flush();
        }

        inputFile.close();

        outputFile.close();

        return true;
    } else
        return false;
}

替代code:

Alternative code used:

FileInputStream inputFile = new FileInputStream(sourceFile);

或者

InputStream inputFile = ClassLoader.class.getResourceAsStream(""+sourceFile);

或者

InputStream inputFile = FileSaving.class.getResourceAsStream(""+sourceFile);

原来的code和在Eclipse中每一个替代工作,并停止出口时工作。

Original code and every alternative work in Eclipse and stop working when exported.

推荐答案

这code是寻找类路径上的一个文件。如果没有一个文件有它抛出FNF。当您在Eclipse中工作,你的文件可能是在src,因此它复制到仓。你归档到一个JAR文件后,您可以访问它要么的getResource 的getResourceAsStream

This code is looking a file on the classpath. If there's no a file there it throws FNF. When you work in Eclipse your file is probably in the src, so it's copied to bin. After you archived a file to the jar you can access it either getResource or getResourceAsStream

InputStream inputFile = this.getClass().getClassLoader().getResourceAsStream(sourceFile.getName())

或使用URL。例如:

URL url = new URL("jar:file:/c:/path/to/my.jar!/myfile.txt"); 
JarURLConnection conn = (JarURLConnection)url.openConnection();
InputStream inputFile = conn.getInputStream();

这篇关于导出的.jar当FileNotFoundException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆