这是我的代码 - 我试图通过数组读取文件来反转文件的内容。
是否有更有效,更快捷的方法来实现这一目标?我觉得这种问题太过分了吗?
class ReverseNumbers {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("numbers.txt");
Scanner Scan = new Scanner(file);
int numoflines = 0;
while(Scan.hasNextLine()) {
Scan.nextLine();
numoflines++;
}
Scan.close();
Scan = new Scanner(file);
int buffer[] = new int[numoflines]; //size
for(int i=0; i<buffer.length; i++) {
buffer[i] = Scan.nextInt();
}
for(int i=buffer.length-1; i>=0; i--) {
int reverse = buffer[i];
System.out.println(reverse);
}
}
}
答案 0 :(得分:0)
import java.io.*;
import java.util.*;
class FileReaderReverse
{
public static void main(String[] args) throws IOException,FileNotFoundException
{
FileReader fr=new FileReader("abcd.txt");
BufferedReader br=new BufferedReader(fr);
String s;
List<String> tmpr = new ArrayList<String>();
do
{
s = br.readLine();
tmpr.add(s);
}while(s!=null);
for(int i=tmpr.size()-1;i>=0;i--) {
System.out.println(tmpr.get(i));
}
}
}
快速尝试此代码。