简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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