user2638180
user2638180

Reputation: 1023

How to get file content properly from a jpg file?

I'm trying to get content from a jpg file so I can encrypt that content and save it in another file that is later decrypted.

I'm trying to do so by reading the jpg file as if it were a text file with this code:

   String aBuffer = "";
   try {
        File myFile = new File(pathRoot);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
        String aDataRow = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow;
        }
        myReader.close();
        } catch (FileNotFoundException e) {
              e.printStackTrace();
        } catch (IOException e) {
              e.printStackTrace();
        }

But this doesn't give the content the file has, just a short string and weirdly enough it also looks like just reading the file corrupts it.

What could I do so I can achieve the desired behavior?

Upvotes: 0

Views: 584

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502036

Image files aren't text - but you're treating the data as textual data. Basically, don't do that. Use the InputStream to load the data into a byte array (or preferably, use Files.readAllBytes(Path) to do it rather more simply).

Keep the binary data as binary data. If you absolutely need a text representation, you'll need to encode it in a way that doesn't lose data - where hex or base64 are the most common ways of doing that.

You mention encryption early in the question: encryption also generally operates on binary data. Any encryption methods which provide text options (e.g. string parameters) are just convenience wrappers which encode the text as binary data and then encrypt it.

and weirdly enough it also looks like just reading the file corrupts it.

I believe you're mistaken about that. Just reading from a file will not change it in any way. Admittedly you're not using try-with-resources statements, so you could end up keeping the file handle open, potentially preventing another process from reading it - but the content of the file itself won't change.

Upvotes: 4

Related Questions