12

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

IAdapter
  • 59,319
  • 71
  • 171
  • 240
Enrique San Martín
  • 2,084
  • 7
  • 28
  • 50

4 Answers4

29

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]);
polygenelubricants
  • 364,035
  • 124
  • 554
  • 617
6
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.

Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
2

Have you read the Java tutorial?

For example:

Path file = ...;
InputStream in = null;
try {
    in = file.newInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException x) {
    System.err.println(x);
} finally {
    if (in != null) in.close();
}
JRL
  • 74,629
  • 18
  • 94
  • 144
  • 1
    yeah, i read the java tutorial and others books, this don't resolve the problem because i want to put all the lines of the file in an Array of strings like: String [] content = new String[lenght_of_the_string]; int i = 0; while ((line = reader.readLine()) != null { content[i] = line; i++; } – Enrique San Martín Jun 04 '10 at 19:48
-1

Set up a BufferedReader to read from the file, then pick up lines from from the buffer however many times.

crazyscot
  • 11,539
  • 2
  • 37
  • 40