0

My application will check if a Properties file exists and create one if not.

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

But when i try to read the properties file like this i get a Null pointer.

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

It fails on the InputStream input line but i dont know why. the file exists and my application can access it because it put it there in the first place. What am i doing wrong?

The file has to be in a location that is accessible to users to change parameters.

enter image description here

Display Name
  • 405
  • 6
  • 26

3 Answers3

5

getResourceAsStream method needs a "class-path relative" name. You are providing an absolute path. Try to use FileInputStream instead.

E.g:

InputStream input = new FileInputStream("c:\\temp\\LaserController.properties");
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
  • 1
    "It fails on the InputStream input line" most alikely this is the case, after that is fixed, the OP should read my answer. +1 – Peter Lawrey Nov 10 '16 at 09:21
3

I suggest using Properties.save() to ensure it is written in a format when can be read.

I suggest you look at the text file to see what was written.

BTW The properties are case sensitive. you write

Comport
parity
baud

but you read

Comport+"comport"
Parity
Baud

so they will all be null.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Move that file to resource folder or add that folder as resource folder

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