SuperStar
SuperStar

Reputation: 57

Java: Parse input file and extract column values

Here is a sample input text file:

some text
one more line of text
another line
and one more
1 23 3
2 34 4
5 12 4
3 23 8

I need to extract each column of numerical values and perform some mathematical operation on it.

This is what i have tried till now:

Path inputFile = Paths.get(args[0]);

            try{
                ArrayList<String> lines = (ArrayList<String>) Files.readAllLines(inputFile, Charset.defaultCharset());
                ArrayList<String []> columns = new ArrayList<>();
                for(String line : lines){
                    columns.add(line.split("\\s"));
                }
                // Now for each line you have columns.
                for(String [] s : columns){ 
                    System.out.println(Arrays.toString(s));
                }

But its just not right and i'm unable to move from this deadlock. Any help would be greatly appreciated..

Upvotes: 0

Views: 1909

Answers (1)

Sujoy
Sujoy

Reputation: 842

I would say ...

for(String line : lines){
                // Just add this condition
                if(line.matches("^[0-9]"){
                    // then process the way you want to...
                }   
            }

Hope this helps...

Edited:

Path inputFile = Paths.get(args[0]);

    try{
        ArrayList<String> lines = (ArrayList<String>) Files.readAllLines(inputFile, Charset.defaultCharset());
        ArrayList<String []> columns = new ArrayList<>();
        for(String line : lines){
            if(line.matches("^[0-9]")){
                System.out.println("Line:"+line);
                String[] colms = line.split("\\s+");
                    columns.add(colms);
                for (int i = 0; i < colms.length; i++) {
                    String temp = colms[i];
                    System.out.println("Colmns:"+i+":"+temp);
                    // process temp one by one
                }
            }
        }
    }catch(Exception ex){
        ex.printStackTrace();
        System.out.println("Exception...");
    }

Upvotes: 1

Related Questions