Hi i want to read a txt file with N lines and the result put it in an Array of strings.
Asked
Active
Viewed 7.9k times
12
-
3Now we know what you want, what is your question? :) – OscarRyz Jun 04 '10 at 19:21
-
1Here's some alternatives ( they just need a little tweak ) http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file – OscarRyz Jun 04 '10 at 19:23
-
And another: http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html – OscarRyz Jun 04 '10 at 19:26
4 Answers
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
-
1
-
3@Enrique: read the API about how `Scanner` handles `IOException`. – polygenelubricants Jun 04 '10 at 19:49
-
-
you can use a for over an array, in eclipse you can use the autocomplete fuction for an example like: https://ideone.com/ZMTesT – Enrique San Martín May 20 '18 at 05:39
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
-
1yeah, 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