Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multiline text with values separated by whitespaces

I have a following test file :

Jon Smith 1980-01-01
Matt Walker 1990-05-12

What is the best way to parse through each line of this file, creating object with (name, surname, birthdate) ? Of course this is just a sample, the real file has many records.

like image 657
mastodon Avatar asked Oct 24 '10 15:10

mastodon


2 Answers

 import java.io.*;
 class Record
{
   String first;
   String last;
   String date;

  public Record(String first, String last, String date){
       this.first = first;
       this.last = last;
       this.date = date;
  }

  public static void main(String args[]){
   try{
    FileInputStream fstream = new FileInputStream("textfile.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    while ((strLine = br.readLine()) != null)   {
       String[] tokens = strLine.split(" ");
       Record record = new Record(tokens[0],tokens[1],tokens[2]);//process record , etc
    }
    in.close();
    } catch (Exception e){
      System.err.println("Error: " + e.getMessage());
    }
 }
}
like image 85
Brandon Frohbieter Avatar answered Oct 06 '22 00:10

Brandon Frohbieter


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerReadFile {
    public static void main(String[] args) {
        //
        // Create an instance of File for data.txt file.
        //
        File file = new File("tsetfile.txt");

        try {
            //
            // Create a new Scanner object which will read the data from the 
            // file passed in. To check if there are more line to read from it
            // we check by calling the scanner.hasNextLine() method. We then
            // read line one by one till all line is read.
            //
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

This:

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();

Could also be changed to

        while (scanner.hasNext()) {
            String line = scanner.next();

Which will read whitespace.

You could do

Scanner scanner = new Scanner(file).useDelimiter(",");

To do a custom delimiter

At the time of the post, now you have three different ways to do this. Here you just need to parse the data you need. You could read the the line, then split or read one by one and everything 3 would a new line or a new person.

like image 27
Matt Avatar answered Oct 06 '22 00:10

Matt