Search code examples
javastringbufferedreadertrim

Java Read numbers from txt file


Let's assume we have a text file like this one:

#this is a config file for John's server


MAX_CLIENT=100

  # changed by Mary


TCP_PORT = 9000

And I have written the following code :

 this.reader = new BufferedReader(new FileReader(filename));
    String line;

    line = reader.readLine();
    while (line.length() != 0) {

        line = line.trim();
        if (line.contains("#") || line.contains("")) {
            line = reader.readLine();

        } else {
            if (line.contains("MAX_CLIENT=")) {
                line = line.replace("MAX_CLIENT=", "");
                this.clientmax = Integer.parseInt(line);
            }

            if (line.contains("TCP_PORT=")) {

                line = line.replace("TCP_Port=", "");
                tcp_port = Integer.parseInt(line);
            }

        }
    }

where clientmax and tcp_port are of type int.

Will clientmax and tcp_port receive their value for this code?

What should I do if I the text file changes a little bit to:

MAX_CLIENT=100# changed by Mary

containing a comment after the number.

ow,btw # represents the start of a comment.

Thank you.


Solution

  • You should use a class designed for this purpose: Properties

    This class handles comments for you so you don't have to worry about them.

    You use it like this:

    Properties prop = new Properties();
    prop.load(new FileInputStream(filename));
    

    Then you can extract properties form it using:

    tcpPort = Integer.parseInt(prop.getProperty("tcpPort"));
    

    Or save using:

    prop.setProperty("tcpPort", String.valueOf(tcpPort));