Examples for Reading a file into an arraylist.

1. Using FileReader
2. Using BufferedReader
3. Using Scanner(String and int)
4. Using Files.readAllLines
This commit is contained in:
RanjeetKaur17
2018-07-30 23:48:50 +04:00
committed by José Carlos Valero Sánchez
parent 43f4ef8e3c
commit c9e901abbe
7 changed files with 171 additions and 0 deletions
@@ -0,0 +1,37 @@
package com.baeldung.fileparser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FileReaderExample {
private static final String FILENAME = "src/resources/txt.txt";
public static void main(String[] args) {
try {
System.out.println(generateArrayListFromFile(FILENAME));
} catch (IOException e) {
e.printStackTrace();
}
}
private static ArrayList<Character> generateArrayListFromFile(String filename) throws IOException {
ArrayList<Character> result = new ArrayList<>();
try (FileReader f = new FileReader(filename)) {
while (f.ready()) {
char c = (char) f.read();
if (c != ' ' && c != '\t' && c != '\n') {
result.add(c);
}
}
return result;
}
}
}