簡體   English   中英

Java文件反向讀寫[逐字節]

[英]Java File read and write in reverse [byte by byte]

我需要從這個文本文件source.txt讀取並在這個文本文件destination.txt中反向寫入內容。 讀取和寫入必須使用逐字節完成!

我使用BufferedReaderBufferedWriter進行了這個練習,它為您提供了一整行作為字符串,然后反轉它非常簡單!

但是我不知道如何使用逐字節逆序寫入! 感謝您的幫助!

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM