Timothy Klim
Timothy Klim

Reputation: 1267

Read binary file as byte[] and send from servlet as char[]

I have a servlet which reads BINARY file and sends it to a client.

byte[] binaryData = FileUtils.readFileToByteArray(path);
response.getWriter().print(new String(binaryData));

It works for NON BINARY files. When I have a BINARY file, I get receive file length bigger than origin or received file not the same. How I can read and send binary data?

Thanks.

Upvotes: 1

Views: 1478

Answers (2)

Roger Lindsjö
Roger Lindsjö

Reputation: 11543

Do not use Writer, it will add encoding of your characters and there will not always be a 1:1 mapping (as you have experienced). Instead use the OutputStream directly.

And avoid reading the full content if you don't need it available at once. Serving many parallel requests will quickly consume memory. FileUtils have methods for this.

FileUtils.copyFile(path, response.getOutputStream());

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500225

Not via the Writer. Writers are for text data, not binary data. Your current code is trying to interpret arbitrary binary data as text, using the system default encoding. That's a really bad idea.

You want an output stream - so use response.getOutputStream(), and write the binary data to that:

response.getOutputStream().write(FileUtils.readFileToByteArray(path));

Upvotes: 8

Related Questions