How to read a text file into ArrayList inwards Java

Prior to Java 7, reading a text file into an ArrayList involves lot of boiler plate coding, every bit you lot ask to read the file employment yesteryear line as well as insert each employment into an ArrayList, but from Java vii onward, you lot tin purpose the utility method Files.readAllLines() to read all lines of a text file into a List. This method provide a List of String which contains all lines of files. Later you lot tin convert this List to ArrayList, LinkedList, or whatever listing you lot desire to. Btw, this the 4th article inwards the serial of reading a text file inwards Java. In the before parts, you lot create got learned how to read a file using Scanner as well as BufferedReader(1). Then, reading the whole file every bit String (2) as well as in conclusion reading a text file into array (3). This plan is non rattling unlike from those inwards damage of fundamentals. We are all the same going to purpose read() method for Java half-dozen solution as well as volition read all text until this method provide -1 which signals the cease of file.



Reading text file into ArrayList inwards Java 6

If you lot know how to read a file employment yesteryear line, either yesteryear using Scanner or yesteryear using BufferedReader thus reading a text file into ArrayList is non hard for you. All you lot ask to produce is read each employment as well as shop that into ArrayList, every bit shown inwards next example:

    BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));     ArrayList<String> listOfLines = new ArrayList<>();      String employment = bufReader.readLine();     while (line != null) {       listOfLines.add(line);       employment = bufReader.readLine();     }      bufReader.close();

Just retrieve to unopen the BufferedReader 1 time you lot are done to forestall resources leak, every bit you lot don't create got try-with-resource contestation inwards Java 6.




Reading text file into List inwards Java 7

In Java 7, you lot don't ask to write code to read as well as shop into ArrayList, but telephone band the Files.readAllLines() method as well as this volition provide you lot a List of String, where each chemical constituent is corresponding employment from the line. Since List is an ordered collection the social club of lines inwards file is preserved inwards list. You tin later on convert this List to ArrayList or whatsoever other implementation.

hither is sample code to read text file into List inwards JDK 7:

public static List<String> readFileIntoList(String file) {     List<String> lines = Collections.emptyList();     try {       lines = Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8);     } catch (IOException e) {       // TODO Auto-generated choose grip of block       e.printStackTrace();     }     return lines;   }

The readAllLines() method accepts a CharSet, you lot tin purpose a pre-defined grapheme gear upward e.g. StandardCharsets.UTF_8 or StandardCharsets.UTF_16.  See Core Java for the Impatient to acquire to a greater extent than virtually novel file utility classes introduced inwards Java vii as well as 8.

 reading a text file into an ArrayList involves lot of boiler plate coding How to read a text file into ArrayList inwards Java




Java Program to read text file into ArrayList

Here is the consummate Java plan to demonstrate both methods to read a text file into ArrayList. This plan starting fourth dimension learn you lot how to produce this inwards JDK vii or Java 8 using Files.readAllLines() method as well as later on using BufferedReader as well as ArrayList inwards Java half-dozen as well as lower version. You tin compile as well as run this plan from ascendency prompt or if you lot desire to run inwards Eclipse, but re-create as well as glue inwards Eclipse Java project. The Eclipse IDE volition automatically create origin file for you. Then but correct click as well as Run every bit Java Program. Make certain you lot create got file.txt inwards your classpath. Since I create got given the relative path here, brand certain you lot position that file within Eclipse projection directory.

 reading a text file into an ArrayList involves lot of boiler plate coding How to read a text file into ArrayList inwards Java



Reading text file into ArrayList inwards Java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List;  /*  * Java Program read a text file into ArrayList inwards Java half-dozen  * as well as Java 8.   */  public class ReadFileIntoArrayList {    public static void main(String[] args) throws Exception {      // reading text file into List inwards Java 7     List<String> lines = Collections.emptyList();     try {       lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     } catch (IOException e) {       // TODO Auto-generated choose grip of block       e.printStackTrace();     }      System.out.println("Content of List:");     System.out.println(lines);      // reading text file into ArrayList inwards Java 6     BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));     ArrayList<String> listOfLines = new ArrayList<>();      String employment = bufReader.readLine();     while (line != null) {       listOfLines.add(line);       employment = bufReader.readLine();     }      bufReader.close();     System.out.println("Content of ArrayLiList:");     System.out.println(listOfLines);    }  }   Output Content of List: [Python, Ruby, JavaScript] Content of ArrayLiList: [Python, Ruby, JavaScript]



That's all virtually how to read a text file into ArrayList inwards Java. You tin run into its rattling slow inwards Java vii as well as Java 8 yesteryear using Files.readAllLines() method. Though you lot should hold upward mindful of grapheme encoding piece reading text file inwards Java. In Java half-dozen also, the solution using BufferedReader or Scanner is non rattling hard to implement, but the affair you lot ask to retrieve is that you lot are loading the whole file into memory. If file is also large as well as you lot don't create got plenty memory, your plan volition come about throwing java.lang.OutOfMemoryError: Java Heap Space. In short, this solution is solely skilful for pocket-sized file, for large file you lot should ever read yesteryear streaming.

Subscribe to receive free email updates:

0 Response to "How to read a text file into ArrayList inwards Java"

Posting Komentar