12

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

3

4 Answers 4

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]);
Sign up to request clarification or add additional context in comments.

4 Comments

this is the answer, thanks men :)
@Enrique: read the API about how Scanner handles IOException.
How to print all elements of String[] arr?
you can use a for over an array, in eclipse you can use the autocomplete fuction for an example like: ideone.com/ZMTesT
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.

1 Comment

looks like this method is deprecated now.
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();
}

1 Comment

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++; }
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.