To read a file to an array, add all lines to a
List
via BufferedReader.readLine
, then convert it to an array with toArray
.Here's how you do it:
// [file.txt]
// item one
// item two
// item three
BufferedReader reader = new BufferedReader(new FileReader(new File("/Users/xero/file.txt")));
List<String> items = new ArrayList<>();
try (reader) {
String line;
while ((line = reader.readLine()) != null) {
items.add(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
String[] itemsInArray = items.toArray(new String[]{});
System.out.println(Arrays.toString(itemsInArray)); // [item one, item two, item three]
What if my delimiter is not a new line?
You can use Scanner
instead of BufferedReader
:
// [file.txt]
// item one ; item two ; item three
Scanner scanner = new Scanner(new File("/Users/xero/file.txt")).useDelimiter(" ; ");
List<String> items = new ArrayList<>();
try (scanner) {
while (scanner.hasNext()) {
items.add(scanner.next());
}
}
String[] itemsInArray = items.toArray(new String[]{});
System.out.println(Arrays.toString(itemsInArray)); // [item one, item two, item three]