Reputation: 3422
How do I read the contents of a text file line by line into String
without using a BufferedReader
?
For example, I have a text file that looks like this inside:
Purlplemonkeys
greenGorilla
I would want to create two strings
, then use something like this
File file = new File(System.getProperty("user.dir") + "\Textfile.txt");
String str = new String(file.nextLine());
String str2 = new String(file.nextLine());
That way it assigns str
the value of "Purlplemonkeys"
, and str2
the value of "greenGorilla"
.
Upvotes: 2
Views: 30166
Reputation: 4506
If you use Java 7 or later
List<String> lines = Files.readAllLines(new File(fileName).toPath());
for(String line : lines){
// Do whatever you want
System.out.println(line);
}
Upvotes: 3
Reputation: 1274
You can use apache.commons.io.LineIterator
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
it.close();
}
One can also validate line by overriding boolean isValidLine(String line)
method.
refer doc
Upvotes: 1
Reputation: 549
You should use an ArrayList
.
File file = new File(fileName);
Scanner input = new Scanner(file);
List<String> list = new ArrayList<String>();
while (input.hasNextLine()) {
list.add(input.nextLine());
}
Then you can access to one specific element of your list from its index as next:
System.out.println(list.get(0));
which will give you the first line (ie: Purlplemonkeys)
Upvotes: 7
Reputation: 1407
You can read text file to list:
List<String> lst = Files.readAllLines(Paths.get("C:\\test.txt"));
and then access each line as you want
P.S. Files - java.nio.file.Files
Upvotes: 8
Reputation: 23415
Sinse JDK 7 is quite easy to read a file into lines:
List<String> lines = Files.readAllLines(new File("text.txt").toPath())
String p1 = lines.get(0);
String p2 = lines.get(1);
Upvotes: 2
Reputation: 3785
File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
System.out.println(input.nextLine());
}
Upvotes: 0
Reputation: 13858
How about using commons-io:
List<String> lines = org.apache.commons.io.IOUtils.readLines(new FileReader(file));
//Direct access if enough lines read
if(lines.size() > 2) {
String line1 = lines.get(0);
String line2 = lines.get(1);
}
//Iterate over all lines
for(String line : lines) {
//Do something with lines
}
//Using Lambdas
list.forEach(line -> {
//Do something with line
});
Upvotes: 1