【问题标题】:FileNotFoundException when exporting .jar导出 .jar 时出现 FileNotFoundException
【发布时间】:2012-08-15 01:50:22
【问题描述】:

在我的客户端/服务器应用程序中,我需要将一些文件(.txt.doc 等)从客户端发送到服务器。当我在 Eclipse 中运行我的代码时它可以工作,但是当我导出 Applet 的签名 JAR 时它不会。它抛出一个FileNotFoundException。我尝试以多种方式保存文件,但均未成功。

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 中工作,并在导出时停止工作。

【问题讨论】:

  • 如果您的应用程序动态创建数据,您应该使用系统特定的存储来存储应用程序数据。某种java.io.tmpdiruser.home。不要试图在 .jar 中找到它们,因为它没有用。

标签: java jar applet inputstream filenotfoundexception


【解决方案1】:

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

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

【讨论】:

  • 您好,我收到此错误:方法 getInputStream() 未定义为 File 类型
  • 我尝试使用您的代码,但我不明白如何将它与我的代码合并。你愿意为我做吗?谢谢
  • 同样的结果,eclipse上OK,Jar上KO。
  • 对 2 种类型的文件进行了几次尝试:IO error write: playbasket_8.doc IO error write: playbasket_8.pdf(在 eclipse 上运行,我在控制台上收到这些错误,但文件在文件系统中正确创建)
  • 我已经签了我的,实际上它并没有抛出任何安全异常。
【解决方案2】:

我发疯后找到了解决办法。 Windows 没有打开文件的权限。 因此,以管理员权限运行您的浏览器,它就会工作。

【讨论】:

    【解决方案3】:

    您需要手动将资源复制到 jar 中。

    为此,请使用 7zip 或 winRar 或其他任何工具,右键单击并“打开存档”。 然后将您的资源(例如 png 等)拖放到适当的文件夹(通常是根目录)。

    【讨论】:

    • 也许这会起作用,但我的应用程序会“动态地”创建资源。
    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 2017-06-05
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    相关资源
    最近更新 更多