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

我有一个以下测试文件:

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

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

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

这个:

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

也可以改为

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

哪个会读取空格。

你可以做到

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

要做自定义分隔符

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

乍一看,我建议StringTokenizer在这里是你的朋友,但是在商业应用程序中有一些实际操作的经验,你可能无法保证的是Surname是一个单一的名字(即有一个双管姓氏的人,没有连字符会导致你的问题。

如果您可以保证数据的完整性,那么您的代码就是

 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,其间的所有字符都是姓氏。

使用FileReader从文件中读取字符,使用BufferedReader缓冲这些字符,以便您可以将它们作为行读取。 然后你有一个选择..我个人使用String.split()来分割空白,给你一个很好的字符串数组,你也可以对这个字符串进行标记。

当然,你必须考虑如果有人有中间名等会发生什么。

看看BufferedReader类。 它有readLine方法。 然后,您可能希望使用空格分隔符拆分每一行以构造获取每个单独的字段。