[英]Java File read and write in reverse [byte by byte]
我需要從這個文本文件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);
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.