2

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(); } } } } 
7
  • what did you reverse byte-by-byte ? Commented Mar 7, 2018 at 10:51
  • Read the file into a byte array and then write out the byte array in the reverse order. Commented Mar 7, 2018 at 10:52
  • 1
    You are looking for RandomAccessFile Commented Mar 7, 2018 at 10:53
  • If your file is in ASCII, then it's pretty simple - every byte is basically the same as a char. If it's UTF-8 or other multibyte encoding, it may be a challenge. Anyway, hint: keep the bytes you read until you reach the end of a line or the end of the file. Commented Mar 7, 2018 at 11:42
  • @RealSkeptic: If what is asked for is byte for byte reversal, encoding does not matter, the file should be processed at a byte level as is it was binaty. Commented Mar 7, 2018 at 12:30

1 Answer 1

3

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); } ... 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.