问题
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"
.
回答1:
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)
回答2:
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
回答3:
If you use Java 7 or later
List<String> lines = Files.readAllLines(new File(fileName));
for(String line : lines){
// Do whatever you want
System.out.println(line);
}
回答4:
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);
回答5:
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
});
回答6:
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
回答7:
File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
System.out.println(input.nextLine());
}
来源:https://stackoverflow.com/questions/34208962/read-a-text-file-line-by-line-into-strings