简体   繁体   中英

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

I need to read from this text file source.txt and write the content in reverse in this text file destination.txt . The read and write must be done using byte-by-byte!

I did this exercise using BufferedReader & BufferedWriter which gives you a whole line as a string then it's very simple to reverse it!

But I don't know how to write in reverse order using byte-by-byte! Thank you for your help!

source.txt has this text: "Operating Systems"

And the result on destination.txt should be the reverse of source.txt : "smetsyS gnitarepO"

Here's the code:

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();
            }
        }
    }
}

You can use RandomAccesFile for reading:

...
            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);
            }
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM