Skip to content
Advertisement

How can I read a file containing text and image data?

I’ve got a file with the following structure:

JavaScript

For example:

JavaScript

I write the example above like this:

JavaScript

This works fine. However, I do not know how to read the file. The problem is that I need to call ImageIO.read() to parse the image, but I can’t call it with a BufferedReader. My draft looks like this:

JavaScript

So: How can I read the image (using ImageIO)?

Any help is very appreciated 🙂


EDIT: Like I do the writing with two different Writers, is it possible to make use of two Readers while reading? Like “Read 3 lines of Strings, then read one line of binary data”.

Advertisement

Answer

The problem, as I can see it, is the mixing of the readers and streams..

Now, I tried using…

JavaScript

To write the file. The hope was that the input stream position would be updated and the content would be written to the end of the file…

And

JavaScript

To read it.

But this didn’t seem to work. What “might” be happening is the file position isn’t being updated to the correct position that we need it to read the image properly.

What I did instead was this…

JavaScript

Basically, I just used the OutputStream and InputStream directly…

Updated

The file contents starts with…

JavaScript

Welcome to 2021

So, the ordinal answer was made some time ago, the world has moved on. Unless you have a very specific need not to (ie transport speed/bandwidth restrictions), I would highly recommend making use of things like JSON and Base64 to send binary and text mixed together.

The main reason, it’s actually much simpler to encode/decode and maintain. The original solution is rather difficult to add new content to, as both ends need to be able to support the changes, where as something like JSON can (if done properly) get away with adding and removing content. It’s also easier to build much more complex parsing workflows, as you’re not reliant on the “read/write” position of the stream.

This example makes use of the org.json library, but you can use what ever library you want.

JavaScript

What if I want to send 2 files?

Then use a JSONArray. org.json is reasonably powerful, see Introduction to JSON-Java for more details. The Google implementation (GSON?) also provides a lot of functionality which can be used to encode/decode json from/to POJOs, if that’s your thing

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement