开发者

read lines in txt file [java] [duplicate]

This question already has answers here: Java: Reading a file into an array (5 answers) Closed 1 year ago.

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 len开发者_运维问答gth.

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


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);
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜