Reversing a file(image,music) in Java corrupts the file

56 views Asked by At

I have written a program that inputs a file, reverses the bytes and writes that into another file. Then. it reverses the reversed file and outputs it into another file. However, in in the end, when I am supposed to get the same file again, it comes back corrupted. I have searched this up and couldn't find a solution.

The reversing code is working. I have tested it. I would be very happy if you tell me what I am doing wrong/missing.

try {
        URL image = new URL(path);
        fis = image.openStream();
        fos = new FileOutputStream(output);
        while (-1 != (b = fis.read(bytes))) {
            sum += b;
            System.out.println("Bytes being written: " + b);
            fos.write(bytes, 0, b);
        }
        JOptionPane.showConfirmDialog(null, "File " + new File(output).getAbsoluteFile() + " successfully downloaded.\n File size in bytes is :" + sum);
        //Algorithm part
        cSum = sum;
        System.out.println("Byte size=" + sum);
        sum = 0;
        cBytes = new byte[cSum];
        revBytes = new byte[cSum];
        bais = new ByteArrayInputStream(cBytes);
        revBytes = CDIP.algo(cBytes);
        fos = new FileOutputStream("Reversed" + output);
        while (-1 != (b = bais.read(revBytes))) {
            sum += b;
            System.out.println("Reversed bytes being written: " + b);
            fos.write(revBytes, 0, b);
        }
        JOptionPane.showConfirmDialog(null, "File successfully reversed! Size(in bytes): " + sum);

---The reversing method

private static byte[] algo(byte[] text) {
    if(text==null) {
        return null;
    }
    int length = text.length;
    for (int i = 0; i <= length / 2; i++) {
        byte temp = text[length - i - 1];
        text[length - i -1] = text[i];
        text[i] = temp;
    }
    return text;
}
2

There are 2 answers

3
Joop Eggen On BEST ANSWER

After writing all close fos. This ensures that everything is written to disk.

Then read the bytes from the file, for which there exists a simple function:

byte[] bytes = Files.readAllBytes(Paths.get("..."));
0
laune On

I suppose you should not add byte values b when you need to count the bytes.

Replace

sum += b;

by

sum++;