0

Hello I have the next code:

package com.jucepho;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

class Copy{
public Copy(byte[] buffer,int count) {
    this.buffer = buffer;
    this.count = count;
}
private byte[] buffer;
private int count;

public byte[] getBuffer() {
    return buffer;
}
public int getCount() {
    return count;
}
}

public class ReaderTwo {

public static void main(String[] args) throws IOException {
    InputStream is = new FileInputStream("ex.docx");
     OutputStream os = new FileOutputStream("exBu.docx");
     OutputStream os2 = new FileOutputStream("exBu2.docx");
    ArrayList<Copy> lista = new ArrayList<>();
    byte[] buffer = new byte[4096];
    int count;
    while ((count = is.read(buffer)) > 0)
    {
           os.write(buffer, 0, count);
        lista.add(new Copy(buffer,count));
    }

    for(Copy c: lista) {
        os2.write(c.getBuffer(), 0, c.getCount());
    }


}

}

I want to read a file more than 5 GB in order to save it. So I saw that I have to read it in this way (Encrypting a large file with AES using JAVA)

My question is, why

OutputStream os = new FileOutputStream("exBu.docx");

copy the data good, i mean the file is correct but

OutputStream os2 = new FileOutputStream("exBu2.docx");

is not correct, is corrupted or I don't know why if I am doing the same, right? I am saving in my ArrayList the same information so why my file is corrupted. (and yeah I need to save all the information in an Object called Copy as you see because I will use serialization and save it in other HD)

Thank you

Yussef
  • 610
  • 6
  • 11
  • 1
    Why on earth would you do it this way? Just add `os2.write(buffer, 0, count)` into your copy loop. Don't save entire files in memory. It wastes both time and space. – user207421 Dec 08 '17 at 00:18
  • I want to save it in a file and encrypt it – Yussef Dec 08 '17 at 00:45

1 Answers1

2
new Copy(buffer,count)

This doesn't create a new byte[], it just passes the same array over and over into the Copy instance; next time you read data into that array, you overwrite the contents of the array in all previous Copy instances.

If you want the Copy to remain unchanged, copy the buffer:

new Copy(Arrays.copyOf(buffer, count), count)

(or do it in the constructor: this.buffer = Arrays.copyOf(buffer, count);)

Andy Turner
  • 137,514
  • 11
  • 162
  • 243