Search code examples
javatext-parsingline-processing

Parsing in Java with C style?


I am new to java text parsing and I'm wondering what is the best way to parse a file when the format of each line is known.

I have a file that has the following format for each line:

Int;String,double;String,double;String,double;String,double;String,double

Note how the String,double act as a pair separated by a comma and each pair is separated by a semicolon.

A few examples:

1;art,0.1;computer,0.5;programming,0.6;java,0.7;unix,0.3
2;291,0.8;database,0.6;computer,0.2;java,0.9;undegraduate,0.7
3;coffee,0.5;colombia,0.2;java,0.1;export,0.4;import,0.5

I'm using the following code to read each line:

public static void main(String args[]) {
    try {
        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream("textfile.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console             
            System.out.println(strLine);
        }
        // Close the input stream
        in.close();
    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }   
 }

Thanks in advance :)


Solution

  • You could use the Scanner class, for starters:

    A simple text scanner which can parse primitive types and strings using regular expressions.