-1

So i have a scanner that reads through a text file of many lines using while(file.hasNext()), however after it reaches the end of the text file how do I make it so that I can start reading lines from the beginning again for a separate while loop?

Tanmim Hanifa
  • 73
  • 1
  • 1
  • 9
  • Check this answer, probaly it will helps you http://stackoverflow.com/a/11665098/4060470 – Anton Kolyaev Dec 14 '16 at 11:25
  • create a new instance of Scanner with this file and read again the text file. According number of lines, it would be more efficient to store the information after the first read and to reuse it. – davidxxx Dec 14 '16 at 11:29
  • 1
    Possible duplicate of [Resetting a .nextLine() Scanner](http://stackoverflow.com/questions/13991494/resetting-a-nextline-scanner) – choasia Dec 14 '16 at 11:29

1 Answers1

0

If you want to read multiple files (example, "text1.txt, text2.txt, text3.txt..etc"), this is what you can do:

Implement your file reading within a method such as:

public void readFile(String filename){
    //all the code for file reading goes here
}

String[] filesToRead = new String[]{"text1.txt", "text2.txt", "text3.txt"};
for(int x=0; x<filesToRead.length; x++)    //iterate through the file names
    readFile(filesToRead[x]);              //repeatedly invoked to read various files

Certianly, you may also save the file names within another text file, and just read from there. This way you don't even have to recompile your program when you want to change the list of files to be read.

Example:

FilesToRead.txt

text1.txt
text2.txt
text3.txt
user3437460
  • 17,253
  • 15
  • 58
  • 106