Search code examples
javafilefile-writingfile-read

When reading and writing a file the output changes


I'm trying read a file(doesn't matter the extension) and write after this, but when I do it, the output file is different from the input.

my code is the next:

OutputStream outputStream = null;
FileReader fr = new FileReader("rute\\inputfile.PNG");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line= br.readLine()) != null) {
    content += line;
}

byte[] toBytes= content.getBytes();
InputStream inputStream = new ByteArrayInputStream(toBytes);
try {
    outputStream = new FileOutputStream(new File("rute\\output.PNG"));
    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    outputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}
inputStream.close();

If you ask me why convert into bytes and write from this form, is because I need do something with the data, and I need this conversion. If you tell me that i cant load an image on a String, yes I can do something like that:

File fil = ~~~~;
FileInputStream fis = null;
fis = new FileInputStream(fil);
byte[] bytess = IOUtils.toByteArray(fis);

But I dont want do it by this way because if I want load big files, the heap size is not enough an this could be solved by the "line per line" read.

Thanks for your answers


Solution

  • I will recommend read this question before. Since you are reading binary data into a String you are changing the encoding of that data. So the output will be different.

    Best approach is read binary files as byte arrays. But I will depend which type of transformation/edition/changes you need to do with them.

    UPDATE

    And, of course, you are editing your content before writing

    while ((line= br.readLine()) != null) {
       content += line + "\n";
    }
    

    so the your output file will be different always.

    UPDATE 2

    Since the question/problem is how to read a big binary file, google is usually your friend. Or you can check this other question