Reading multi-line text with spaces separated values

I have the following test file:

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

What is the best way to parse every line of this file by creating an object with (first name, last name, date of birth)? Of course, this is just a sample, the real file has many entries.

+3
source share
5 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 = str.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());
   }
 }
}
+8
source
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();
        }

    }
}

It:

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

You can also change to

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

What will read the spaces.

You could do

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

Make custom separator

. , . , , 3 .

+8

, , StringTokenizer , , , -, , , , , , - ( - , , .

,

BufferedReader read = new BufferedReader(new FileReader("yourfile.txt"));
String line = null;
while( (line = read.readLine()) != null) {
   StringTokenizer tokens = new StringTokenizer(line);
   String firstname = tokens.nextToken();
   ...etc etc
}

, , DOB, .

+1

FileReader , BufferedReader , . . String.split(), , , tokenize .

, , , - ..

+1

BufferedReader. readLine. .

0

Source: https://habr.com/ru/post/1771173/


All Articles