How can I read a file and then add all lines to a string array in java?
Example:
Content from input txt file:
line1fromtxt
line2fromtxt
line3fromtxt
Output:
lines = {"line1fromtxt", "line2fromtxt", "line3fromtxt"};
How can I read a file and then add all lines to a string array in java?
Example:
Content from input txt file:
line1fromtxt
line2fromtxt
line3fromtxt
Output:
lines = {"line1fromtxt", "line2fromtxt", "line3fromtxt"};
You can use Files.readAllLines
to get a List<String>
and then use toArray
to convert that into a String[]
String[] lines = Files.readAllLines(Paths.get(filename)).toArray(new String[0]);
And it would be simpler to use a List rather than an array.
List<String> lines = Files.readAllLines(Paths.get(filename));