Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: how to read a txt file to an Array of strings [duplicate]

Tags:

java

Hi i want to read a txt file with N lines and the result put it in an Array of strings.

like image 492
Enrique San Martín Avatar asked Jun 04 '10 19:06

Enrique San Martín


2 Answers

Use a java.util.Scanner and java.util.List.

Scanner sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
  lines.add(sc.nextLine());
}

String[] arr = lines.toArray(new String[0]);
like image 103
polygenelubricants Avatar answered Sep 20 '22 15:09

polygenelubricants


FileUtils.readLines(new File("/path/filename"));

From apache commons-io

This will get you a List of String. You can use List.toArray() to convert, but I'd suggest staying with List.

like image 29
Bozho Avatar answered Sep 21 '22 15:09

Bozho