从另一个文件夹读取属性文件时为空指针

Null pointer when reading a Properties file from another folder

我的应用程序将检查属性文件是否存在,如果不存在则创建一个。

try{
        // create new file

        String path="c:\temp\LaserController.properties";
        File file = new File(path);
        String comport = "Comport=COM1";
        String Parity = "parity=none";
        String baud = "baud=9600";
        String Stopbits = "StopBits=0";
        String databits = "DataBits=8";
           // if file doesnt exists, then create it
           if (!file.exists()) {
               file.createNewFile();



           FileWriter fw = new FileWriter(file.getAbsoluteFile());
           BufferedWriter bw = new BufferedWriter(fw);
           // write in file
           bw.write(comport);
           bw.newLine();
           bw.write(Parity);
           bw.newLine();
           bw.write(baud);
           bw.newLine();
           bw.write(Stopbits);
           bw.newLine();
           bw.write(databits);
           // close connection
           bw.close();
           }

但是当我尝试像这样读取属性文件时,我得到了一个 Null 指针。

else {
           Properties prop = new Properties();


            InputStream input = LaserControllerUI.class.getResourceAsStream("c:\temp\LaserController.properties");


            // load a properties file
            prop.load(input);

            // get the property value and print it out
            System.out.println(prop.getProperty(Comport+"comport"));
            System.out.println(prop.getProperty("Parity"));
            System.out.println(prop.getProperty("Baud"));
            input.close();

        }
     }catch(Exception e){
         System.out.println(e);
     }
}       

它在 InputStream input 行失败,但我不知道为什么。该文件存在并且我的应用程序可以访问它,因为它首先将它放在那里。我做错了什么?

该文件必须位于用户可以访问以更改参数的位置。

getResourceAsStream 方法需要一个 "class-path relative" 名称。您正在提供绝对路径。尝试使用 FileInputStream 代替。

例如:

InputStream input = new FileInputStream("c:\temp\LaserController.properties");

我建议使用 Properties.save() 以确保以可读的格式编写。

我建议你查看文本文件,看看写了什么。

顺便说一句,这些属性区分大小写。你写

Comport
parity
baud

但你阅读

Comport+"comport"
Parity
Baud

所以他们都是null

将该文件移动到资源文件夹或将该文件夹添加为资源文件夹

getClass().getClassLoader().getResourceAsStream("LaserController.properties")