简体   繁体   English

读取txt文件中的行[java]

[英]read lines in txt file [java]

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. 我有一个包含几行数据的txt文件。 example: 例:

123 ralph bose 20000 200 1 2 123 ralph bose 20000 200 1 2

256 ed shane 30000 100 2 4 256 ed shane 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. 但是,我不确定如何一次读取一行,将元素传回另一个类,然后,一旦处理完成,就读取NEXT行。 Method cooperation between my classes works fine (tested) but how do i read one line at a time? 我的类之间的方法合作工作正常(测试),但我如何一次读取一行?

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... 棘手的...

There are lots of ways to read an entire line at a time; 有很多方法可以一次读取整行; Scanner is probably easiest: Scanner可能最简单:

final Scanner s = new Scanner(yourFile);
while(s.hasNextLine()) {
    final String line = s.nextLine();
    YourClass.processLine(line);
}
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. 字符串类split方法。 for splitting depending on space... you can do ... line.split("\\\\s*") 根据空间分裂...你可以做... line.split("\\\\s*")

Hope it works 希望它有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM