How do you read the contents of a file into an ArrayList
in Java?
Here are the file contents:
cat
ho
Add this code to sort the data in text file.
Collections.sort(list);
Simplest form I ever found is...
List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/
enter code here
ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/
while (scr.hasNext()){
list.add(scr.next()); } /*above code is responsible for adding data in arraylist with the help of add function */
A one-liner with commons-io:
List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");
The same with guava:
List<String> lines =
Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
Here's a solution that has worked pretty well for me:
List<String> lines = Arrays.asList(
new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
);
If you don't want empty lines, you can also do:
List<String> lines = Arrays.asList(
new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
);