Hi i want to read a txt file with N lines and the result put it in an Array of strings.
-
3Now we know what you want, what is your question? :)OscarRyz– OscarRyz2010-06-04 19:21:28 +00:00Commented Jun 4, 2010 at 19:21
-
1Here's some alternatives ( they just need a little tweak ) stackoverflow.com/questions/326390/…OscarRyz– OscarRyz2010-06-04 19:23:44 +00:00Commented Jun 4, 2010 at 19:23
-
And another: exampledepot.com/egs/java.io/ReadLinesFromFile.htmlOscarRyz– OscarRyz2010-06-04 19:26:28 +00:00Commented Jun 4, 2010 at 19:26
Add a comment
|
4 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]);
4 Comments
Enrique San Martín
this is the answer, thanks men :)
polygenelubricants
@Enrique: read the API about how
Scanner handles IOException.Chinmoy
How to print all elements of String[] arr?
Enrique San Martín
you can use a for over an array, in eclipse you can use the autocomplete fuction for an example like: ideone.com/ZMTesT
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
Praveen Kumar
looks like this method is deprecated now.
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
Enrique San Martín
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++; }