导出 .jar 时出现 FileNotFoundException [英] FileNotFoundException when exporting .jar

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

问题描述

在我的客户端/服务器应用程序中,我需要从客户端向服务器发送一些文件(.txt.doc 等).当我在 Eclipse 中运行我的代码时,它可以工作,但是当我导出 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;
}

使用的替代代码:

FileInputStream inputFile = new FileInputStream(sourceFile);

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

或者

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

原始代码和所有替代代码在 Eclipse 中都可以工作,并且在导出时停止工作.

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

推荐答案

此代码正在查找类路径上的文件.如果那里没有文件,它会抛出 FNF.当您在 Eclipse 中工作时,您的文件可能在 src 中,因此它会被复制到 bin.将文件归档到 jar 后,您可以访问它 getResourcegetResourceAsStream

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 = 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天全站免登陆