Question

When trying to transfer data from a saved txt file to elements in an ArrayList, I'm running into a rather irritating null problem. It seems that when I use bufferedReader.readLine(), it erases the data in the txt file so that whenever I try to read the file again later in the program, it is just a series of null entries. I believe I need to read the file twice; once to find the number of lines in the txt file, and the second time to then use a for loop to transfer the lines from the txt file to the ArrayList. I've included the code below, so any help and insight would be greatly appreciated! Ultimately I just need to transfer all the data from this txt file to an arrayList...

    System.out.println("What is the name of the file you would like to open?");
    reader.nextLine();
    String name = reader.nextLine() + ".txt";
    System.out.println("Looking for file...");
    try {
      FileReader fr = new FileReader(name);
      BufferedReader buf = new BufferedReader(fr);
      //Create a temporary ArrayList to store data
      ArrayList<String> temp = new ArrayList<String>();

      //Find number of lines in txt file
      int numLine=0;
      String line = null;
      while ((line = buf.readLine()) != null) {
        numLine++;
      }

      //write data from txt file to ArrayList temp
      for (int i = 0; i < numLine; i++) {
          temp.add(buf.readLine());
      }
    }
    catch(IOException e) {
      e.printStackTrace();
    }
    System.out.println("\n *********************");
  }
Was it helpful?

Solution

//Find number of lines in txt file
  int numLine=0;
  String line = null;
  while ((line = buf.readLine()) != null) {
    numLine++;
  }

You don't need the number of lines in the file. Remove all that.

  //write data from txt file to ArrayList temp
  for (int i = 0; i < numLine; i++) {
      temp.add(buf.readLine());
  }

Change that to

String line;
while ((line = buf.readLine()) != null)
{
    temp.add(line);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top