读取多行文本,其值由空格分隔

mas*_*don 4 java string parsing

我有一个以下测试文件:

Jon Smith 1980-01-01
Matt Walker 1990-05-12
Run Code Online (Sandbox Code Playgroud)

解析此文件的每一行,使用(姓名,姓氏,生日)创建对象的最佳方法是什么?当然这只是一个样本,真正的文件有很多记录.

Orb*_*bit 10

 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());
   }
 }
}
Run Code Online (Sandbox Code Playgroud)

  • @Brandon-问题显然有一个'功课'标签......我不认为你通过赠送完整的解决方案让@ mastodon的生活变得更好. (2认同)

Mat*_*att 10

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();
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

这个:

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
Run Code Online (Sandbox Code Playgroud)

也可以改为

        while (scanner.hasNext()) {
            String line = scanner.next();
Run Code Online (Sandbox Code Playgroud)

哪个会读取空格.

你可以做到

Scanner scanner = new Scanner(file).useDelimiter(",");
Run Code Online (Sandbox Code Playgroud)

做自定义分隔符

在发布时,现在有三种不同的方法可以做到这一点.在这里,您只需要解析所需的数据.您可以阅读该行,然后逐个拆分或阅读,所有3将是新行或新人.