JAVA 使用 BufferedReader 逐字读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28684673/
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
JAVA Reading from file word by word using BufferedReader
提问by Liolikas Bramanovas
I have to read from a file Author|Name|Year I need to store this information into class nodes. I must use BufferedReader and FileReader.
我必须从文件 Author|Name|Year 中读取我需要将此信息存储到类节点中。我必须使用 BufferedReader 和 FileReader。
public class Book {
String author, name;
int years;
}
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws Exception{
Book book1 = new Book();
FileReader file = new FileReader("C:/Users/ZatoIndustries/Desktop/failas.txt");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
}
}
Input looks like:A|bbbb|2002
B|cccc|2001
A|dddd|2000
输入看起来像:A|bbbb|2002
B|cccc|2001
A|dddd|2000
回答by mk.
After you read line by line:
逐行阅读后:
String line = reader.readLine();
split each line by |
:
分割每一行|
:
String[] words = line.split("\|");
you can then assign each of these to a descriptive variable, if you'd like:
然后,如果您愿意,您可以将其中的每一个分配给一个描述性变量:
String year = words[2]
This is the easiest way to do this, though you could have a look at Scannerfor something more complicated.
这是执行此操作的最简单方法,但您可以查看Scanner以了解更复杂的内容。