【问题标题】:Run java jar file and path to file it use. (Windows 7 and windows 2008 server)运行 java jar 文件和它使用的文件路径。 (Windows 7 和 Windows 2008 服务器)
【发布时间】:2015-09-11 22:08:29
【问题描述】:

我开发了一个小型 java 应用程序并将其导出到 jar 文件(形式 eclipse)。在这个应用程序中,我使用 xml 文件名从以下位置读取输入数据:

private static final String INPUT_FILE_NAME = "./tasks.xml";

............

    //read input tasks queue
    XMLDecoder decoder = null;
    try {
        decoder = new XMLDecoder(new BufferedInputStream(
                new FileInputStream(INPUT_FILE_NAME)));
        searchTasksQueue = (BlockingQueue<SearchTask>) decoder.readObject();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (decoder != null) {
            decoder.close();
        }
    }

当我运行 jar 文件时,我将任务文件放在与 jar 相同的文件夹中。 在 windows 7 下一切正常。虽然当我在 windows 2008 服务器下做同样的事情时,我得到:

C:\Users\Administrator>java -jar c:\scraper\scraper.jar
java.io.FileNotFoundException: .\tasks.xml (The system cannot find the file spec
ified)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at bmw.scraper.Starter.main(Starter.java:40)

哪里出错了?在 Windows 2008 服务器下运行它需要检查什么?

PS

  • 在我的 Win 7 java 版本“1.8.0_45”上
  • 在 win 2008 服务器 java 版本“1.8.0_60”(通过 RDP 客户端运行)

【问题讨论】:

    标签: java windows jar path


    【解决方案1】:

    如果您的文件在您的 jar 文件夹中,则使用 Classloader 加载您的文件。

    如下图

    InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
    

    而不是

    decoder = new XMLDecoder(new BufferedInputStream(
                    new FileInputStream(INPUT_FILE_NAME)));
    

    您可以使用 fileInputStream 是您正在从外部加载文件。

    检查此解决方案是否适合您。

    【讨论】:

    • 它有效。过一段时间会做更多的测试。你有什么想法为什么在我的帖子中提到的解决方案不能在 win 2008 服务器下工作,而在 windows 7 下工作?
    • 太好了。如果这个答案对您有帮助,请不要忘记接受答案/投票。是的,如果它在 win 7 上工作,那么它也应该在 Win 服务器上工作,这很奇怪。但是我在我的win7机器上做了同样的事情(正如你在问题中提到的那样),我得到了上述错误,所以不知道它是如何为你工作的。但通常每当您从 jar 加载文件时,您都应该使用类加载器。
    猜你喜欢
    • 1970-01-01
    • 2011-02-20
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2011-11-03
    相关资源
    最近更新 更多