2016-11-10 79 views
0

我的应用程序将检查属性文件是否存在,如果不存在则创建一个。从另一个文件夹读取属性文件时的空指针

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

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

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行失败,但我不知道为什么。该文件存在,我的应用程序可以访问它,因为它首先将它放在那里。我究竟做错了什么?

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

enter image description here

+0

'LaserControllerUI' ......这是哪里的类定义,它有什么作用? –

回答

5

getResourceAsStream方法需要一个 “类路径上相对” 的名称。你正在提供一个绝对路径。尝试使用FileInputStream来代替。

E.g:

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

“它在InputStream输入行上失败”这种情况最为常见,在修复之后,OP应该阅读我的答案。 +1 –

3

我建议使用Properties.save()保证何时可以读取它的格式写入。

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

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

Comport 
parity 
baud 

,而是你读

Comport+"comport" 
Parity 
Baud 

所以他们都将null

+0

好的,完成并确定了大小写。它现在打印出空,但如果我点击'comport'它显示写在'属性'文件'comport = COM1'的正确值 –

+0

@DisplayName我猜你不应该查找'Comport +“comport”' –

+0

多数民众赞成我把它改为'comport'当我点击它在日食它会显示我的属性,但它并没有按预期打印出“COM1”。 –

0

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

的getClass()。getClassLoader()。的getResourceAsStream( “LaserController.properties”)

相关问题