Java – Why can’t I read an Integer in the Properties file

file-iojavaproperties

I'm trying to write a configs file in Java and I put my port number inside it for my HTTP Web Server to connect to and also the root path.

Configs file:

root= some root
port=8020

I am trying to access the properties like this:

FileInputStream file = new FileInputStream("config.txt");       
//loading properties from properties file        
config.load(file);

int port = Integer.parseInt(config.getProperty("port"));   
System.out.println("this is port " + port);

If I do it with a single parameter in the getProperty method, I get this error

"java.lang.NumberFormatException: null"

However, if I access it like this

int port = Integer.parseInt(config.getProperty("port", "80"));

it works.

Also, it works for config.getProperty("root"); so I don't understand…

Edit:

import java.net.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;

public class Server
{


    public static void main(String[] args) throws Exception
    {
        boolean listening = true;
        ServerSocket server = null;     
        Properties config = new Properties();
        int port = 0;
        try
        {              
            //Reading properties file
            FileInputStream file = new FileInputStream("config.txt");       
            //loading properties from properties file        
            config.load(file);

            port = Integer.parseInt(config.getProperty("port"));   
            System.out.println("this is port " + port);


            System.out.println("Server binding to port " + port);
            server = new ServerSocket(port);



        }
        catch(FileNotFoundException e)
        {
            System.out.println("File not found: " + e);
        }
        catch(Exception e)
        {
            System.out.println("Error: " + e);
            System.exit(1);
        }

        System.out.println("Server successfully binded to port " + port);

        while(listening)
        {
            System.out.println("Attempting to connect to client");
            Socket client = server.accept();
            System.out.println("Successfully connected to client");
            new HTTPThread(client, config).start();
        }

        server.close();
    }

}

Best Answer

Can you provide a self contained example to reproduce your problem?

Sorry, I don't understand

When I run

Properties prop = new Properties();
prop.setProperty("root", "some root");
prop.setProperty("port", "8020");
prop.store(new FileWriter("config.txt"), "test");

Properties config = new Properties();
//loading properties from properties file
config.load(new FileReader("config.txt"));

int port = Integer.parseInt(config.getProperty("port"));
System.out.println("this is port " + port);

I get

this is port 8020