Java 读取值以空格分隔的多行文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4008905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read multiline text with values separated by whitespaces
提问by mastodon
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.
解析此文件的每一行并使用 (name, surname,birthdate) 创建对象的最佳方法是什么?当然这只是一个样本,真实的文件有很多记录。
采纳答案by Orbit
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());
}
}
}
回答by kuriouscoder
Look at BufferedReader
class. It has readLine
method. Then you may want to split each line with space separators to construct get each individual field.
看BufferedReader
课。它有readLine
方法。然后你可能想用空格分隔符分割每一行来构造每个单独的字段。
回答by Codemwnci
At first glance, I would suggest the StringTokenizer would be your friend here, but having some experience doing this for real, in business applications, what you probably cannot guarantee is that the Surname is a single name (i.e. someone with a double barrelled surname, not hyphenated would cause you problems.
乍一看,我建议 StringTokenizer 是你的朋友,但在实际的商业应用中,你可能无法保证姓氏是一个单一的名字(即有双桶姓的人,不连字符会给你带来问题。
If you can guarantee the integrity of the data then, you code would be
如果您可以保证数据的完整性,那么您的代码将是
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
}
If you cannot guarantee the integrity of your data, then you would need to find the first space, and choose all characters before that as the last name, find the last space and all characters after that as the DOB, and everything inbetween is the surname.
如果你不能保证你的数据的完整性,那么你需要找到第一个空格,并选择在它之前的所有字符作为姓氏,找到最后一个空格和之后的所有字符作为DOB,中间的所有字符都是姓氏.
回答by Lee Jarvis
Use a FileReaderfor reading characters from a file, use a BufferedReaderfor buffering these characters so you can read them as lines. Then you have a choice.. Personally I'd use String.split()to split on the whitespace giving you a nice String Array, you could also tokenize this string.
使用FileReader从文件中读取字符,使用BufferedReader缓冲这些字符,以便您可以将它们作为行读取。然后你有一个选择..我个人会使用String.split()来分割空白给你一个很好的字符串数组,你也可以标记这个字符串。
Of course you'd have to think about what would happen if someone has a middle name and such.
当然,您必须考虑如果某人有中间名之类的会发生什么。
回答by Matt
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.
在发布时,现在您可以通过三种不同的方式来执行此操作。在这里你只需要解析你需要的数据。您可以阅读该行,然后拆分或逐个阅读,所有 3 都将是一个新行或一个新人。