read lines in txt file [java]

▼魔方 西西 提交于 2019-11-30 08:53:16

问题


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:

123 ralph bose 20000 200 1 2

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.

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?

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

end_of_file = f1.readRecord(emp);

        if(!end_of_file)
        { 
           slip.printPay(slipWrite);
        }

Class 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...


回答1:


There are lots of ways to read an entire line at a time; Scanner is probably easiest:

final Scanner s = new Scanner(yourFile);
while(s.hasNextLine()) {
    final String line = s.nextLine();
    YourClass.processLine(line);
}



回答2:


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*")

Hope it works



来源:https://stackoverflow.com/questions/4315227/read-lines-in-txt-file-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!