我需要从此文本文件source.txt
读取内容,并将内容反向写入该文本文件destination.txt
。读取和写入必须使用逐字节完成!
我使用 BufferedReader
和 BufferedWriter
完成了这个练习,它为您提供了一整行字符串,然后非常简单地反转它!
但是我不知道如何使用逐字节逆序写入! 感谢您的帮助!
source.txt
包含以下文本:“操作系统”
destination.txt
上的结果应该与 source.txt
相反:“smetsyS gnitarepO”
代码如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("source.txt");
out = new FileOutputStream("destination.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
最佳答案
您可以使用RandomAccesFile进行读取:
...
in = new RandomAccessFile("source.txt", "r");
out = new FileOutputStream("destination.txt");
for(long p = in.length() - 1; p >= 0; p--) {
in.seek(p);
int b = in.read();
out.write(b);
}
...
关于Java文件逆向读写[逐字节],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49150047/