FileNotFoundException when exporting .jar

[亡魂溺海] 提交于 2019-12-02 01:49:14

问题


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;
}

Alternative code used:

FileInputStream inputFile = new FileInputStream(sourceFile);

Or

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

Or

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

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


回答1:


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())

or using URL. For example

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



回答2:


You need to copy your resources manually into the jar.

To do so, use 7zip or winRar or anything else, right click and "open archive". Then drag-and-drop your resouces (e.g. png's etc.) to the appropriate folder (usually root).




回答3:


I found the solution after becoming mad. Windows didn't have privileges to open the files. So run your browser with Administrator privileges and it will work.



来源:https://stackoverflow.com/questions/12025689/filenotfoundexception-when-exporting-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!