简体   繁体   中英

How do I read in a file, each line being an element in an ArrayList in Java?

I want to take a txt file and make each line of that file an element in an ArrayList in order. I also dont want the "\\n" at the end of each line. How would I go about this?

I found this, which can be made with JDK7:

List<String> readSmallTextFile(String aFileName) throws IOException {
    Path path = Paths.get(aFileName);
    return Files.readAllLines(path, ENCODING);
}

And call it with

ArrayList<String> foo = (ArrayList<String>)readSmallTextFile("bar.txt");

After this, you can filter any unwanted chars in each of the lines in the List "foo".

This requires three simple steps: -

  • Read each line from your file
  • Strip the newline from the end
  • Add the line to the ArrayList<String>

You see, I didn't answer your question. I just re-framed it, to look like an answer.

This is how your while loop condition will look like: -

Scanner scanner = new Scanner(yourFileObj);
while (scanner.hasNextLine()) {

    // nextLine automatically strips `newline` from the end
    String line = scanner.nextLine();  

    // Add your line to your list.
}

UPDATE : -

Since you reading your file line by line, it would be better to use BufferedReader . Scanner is better if you want to parse each tokens and do something special with them.

BufferedReader br = new BufferedReader(new FileReader("fileName"));

String line = null;

// readLine also doesn't include the newline in the line read
while ((line = br.readLine()) != null) {  
    //add your line to the list
}

I prefer BufferedReader, it's quicker than Scanner

BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );

reading until end of file is

String line = br.readLine(); // read firt line
while ( line != null ) { // read until end of file (EOF)
    // process line
    line = br.readLine(); // read next line
}

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