简体   繁体   中英

Reading multiple text files java

I'm having trouble on reading multiple text files to fit into one scanner for example I have multiple text files that are named text1.txt , text2.txt etc... I'm trying to make it so that once the user enters which text file number they want it will bring up that data via arrays.

File txt = new File("text.txt");

void readTextFiles() throws IOException {
String line[] = new String[100];
Scanner readTextFiles= new Scanner(txt);

while (readTextFiles.hasNextLine()) {
  line[q] = readTextFiles.nextLine();
  if (line[q].trim() != "") {
    String item[] = line[i].split(" ");
    time[q] = item[0];
    date[q] = item[1];
  }
  q++;

}
readTextFiles.close();
}

my logic works like this but its a code error:

File txt= new File("txt" + textFileNumber + ".txt");
int textFileNumber=0;`

If I understood correctly, the error you got is because the initialisation of the local variable does not precede it's use. You need to declare the textFileNumber before its usage in the string concatenation. Further you are implementing this functionality as a method. So why not make the file number a method parameter?

public void readTextFiles(int fileNumber){
    File txtFile = new File("text" + fileNumber + ".txt");
    //logic
}

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