【问题标题】:how to make a properties file available after building a java application如何在构建 Java 应用程序后使属性文件可用
【发布时间】:2016-01-01 14:20:22
【问题描述】:

我正在开发一个 java swing 应用程序,它工作正常,但是在构建我的应用程序之后,当我运行 jar 文件时,我的应用程序无法按我想要的方式工作。所以要知道我使用这个测试的问题是什么:

FileReader reader;
Properties props;
    try{
         reader = new FileReader("src\\inputs.properties");
         props = new Properties();
         props.load(reader2);

         JOptionPane.showMessageDialog(null,reader.getClass());
  }catch(Exception e){
       JOptionPane.showMessageDialog(null,e.getMessage());
  }

所以当我运行该应用程序时,它运行良好,我收到以下消息: message before building the app

这意味着我的属性文件已加载。

但是当我构建应用程序时,当我运行它时,我会收到以下消息:

message after building the app

我的问题是如何让我的属性文件在构建可能的应用程序后工作?

我正在使用 netbeans,这是我的项目结构:

-源码包
--默认包
-- 输入.属性
--myapppackage
--myapppackage.java

提前致谢。

【问题讨论】:

  • 您能否将错误消息作为文本而不是屏幕截图的链接发布?
  • 是的,这是第一条消息:class java.io.FileReader 第二条消息src\inputs.properties(系统找不到指定的路径)

标签: java swing properties-file


【解决方案1】:

请在您的项目中创建一个文件夹“config”并将inputs.properties 放入其中。

 reader = new FileReader("config/inputs.properties");

详情你也可以浏览这个帖子: Netbeans FileReader FileNotFound Exception when the file is in folder?

或者: 当您的资源在 JAR 文件中时,它不再是文件。文件只是文件系统上的物理文件。解决方案:使用getResourceAsStream。像这样的:

try {

        Properties props;
        Property p=new Property();
        InputStreamReader  in=new InputStreamReader(p.getClass().getResourceAsStream("/config/" + "inputs.properties"));
        props = new Properties();

        props.load(in);

        JOptionPane.showMessageDialog(null, in.getClass());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }

【讨论】:

    【解决方案2】:

    尝试使用它来加载属性文件:

            File file = new File("inputs.properties);//use the right path
            FileInputStream fileInput = new FileInputStream(file);
            Properties properties = new Properties();
            properties.load(fileInput);
            fileInput.close();
    

    【讨论】:

    • 嘿,abdelhak,感谢您的回复,我将路径更改为“inputs.properties”,但现在收到此消息:系统找不到指定的路径。在构建应用之前和之后。
    • @Ali 你在这两种情况下的消息?
    • @Ali 看看上面的答案
    • 感谢 Abdelhak 的回复和您的时间,但现在我确定我的属性文件的正确路径有问题。那么如何加载文件, File file = new File("path");我将属性文件放在我的源包中,并且我希望我的属性文件包含在我的应用程序的主 jar 中,因为我想在其他机器上运行该应用程序。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多