JAVA 打开一个文本文件,每次读取一行内容。将每行作为一个string读入,并将那个string对

2024-11-23 02:39:29
推荐回答(3个)
回答1:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("d:/1.txt"));
String line = null;
LinkedList list = new LinkedList();
while ((line = reader.readLine()) != null) {
list.add(line);
}
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}
reader.close();
}
}

回答2:

Scanner scanner;
try{
scanner=new Scanner(new File("filename"));
}catch(FileNotFoundException e){
e.printStackTrace();
System.out.println("Error openning the file"+filename);
}
LinkedList linkedList = new LinkedList();
while(scanner.hasNextLine()){
linkedList.addLast(scanner.nextLine());
}
scanner.close();
for(String s : linkedList){
System.out.println(s);
}

回答3:

List contents = new ArrayList<>(Files.readAllLines(Paths.get(parent, filename)));
Collections.reverse(contents);
for(String line : contents)
System.out.println(line);

需要jdk7