12

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

IAdapter
  • 62,595
  • 73
  • 179
  • 242
Enrique San Martín
  • 2,202
  • 7
  • 30
  • 51

4 Answers4

30

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
  • 376,812
  • 128
  • 561
  • 623
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
  • 588,226
  • 146
  • 1,060
  • 1,140
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
  • 76,767
  • 18
  • 98
  • 146
  • 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,819
  • 2
  • 39
  • 40