读取 txt 文件中的行 [java]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4315227/
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 lines in txt file [java]
提问by Favonius
I'll try to be as clear as possible but pardon me if my question is not perfect. I have a txt file with several lines of data. example:
我会尽量说清楚,但如果我的问题不完美,请原谅我。我有一个包含多行数据的 txt 文件。例子:
123 ralph bose 20000 200 1 2
123 拉尔夫·博斯 20000 200 1 2
256 ed shane 30000 100 2 4
256 埃德·沙恩 30000 100 2 4
...
...
I need to read each line sequentially and pass it back to a method in a separate class for processing. I know how to break down each line into elements by using StringTokenizer.
我需要按顺序读取每一行并将其传递回单独的类中的方法进行处理。我知道如何使用 StringTokenizer 将每一行分解为元素。
However, i'm not sure how to read one line at a time, pass back the elements to the other class and then, once the processing is done, to read the NEXT line. Method cooperation between my classes works fine (tested) but how do i read one line at a time?
但是,我不确定如何一次读取一行,将元素传回另一个类,然后在处理完成后读取 NEXT 行。我的班级之间的方法合作工作正常(经过测试),但我如何一次阅读一行?
I was thinking of creating an array where each line would be an array element but as the number of lines will be unknown i cannot create an array as i don't know its final length.
我正在考虑创建一个数组,其中每一行都是一个数组元素,但由于行数未知,我无法创建数组,因为我不知道它的最终长度。
Thanks
谢谢
Baba
巴巴
EDIT
编辑
rough setup :
粗略设置:
Class A
A级
end_of_file = f1.readRecord(emp);
if(!end_of_file)
{
slip.printPay(slipWrite);
}
Class B
B级
public boolean readRecord(Employee pers) throws IOException {
boolean eof = false ;
String line = in.readLine() ;
???
}
filename is never passed around
文件名永远不会被传递
so up until here i can read the first line but i think i need a way to loop through the lines to read them one by one with back and forth between classes.
所以直到这里我可以阅读第一行,但我认为我需要一种方法来循环遍历这些行,以便在类之间来回读取它们。
tricky...
棘手...
回答by Michael Mrozek
回答by Favonius
void readLine(String fileName)
{
java.io.BufferedReader br = null;
try
{
br = new java.io.BufferedReader(new java.io.FileReader(fileName));
String line = null;
while(true)
{
line = br.readLine();
if(line == null)
break;
// process your line here
}
}catch(Exception e){
}finally{
if(br != null)
{
try{br.close();}catch(Exception e){}
}
}
}
Also if you want to split strings... use
另外,如果你想分割字符串......使用
String classes split
method. for splitting depending on space... you can do ... line.split("\\s*")
字符串类split
方法。根据空间分割……你可以做……line.split("\\s*")
Hope it works
希望它有效