简体   繁体   English

Java文件反向读写[逐字节]

[英]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 .我需要从这个文本文件source.txt读取并在这个文本文件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!我使用BufferedReaderBufferedWriter进行了这个练习,它为您提供了一整行作为字符串,然后反转它非常简单!

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" source.txt有这样的文字:“操作系统”

And the result on destination.txt should be the reverse of source.txt : "smetsyS gnitarepO"并且destination.txt上的结果应该是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:您可以使用 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