JAVA: Open and read file using InputStreamReader

yakamuki picture yakamuki · Oct 9, 2014 · Viewed 11.4k times · Source

I'm trying to read a binary file (pdf, doc, zip) using InputStreamReader. I achieved that using FileInputStream, and saving the contents of file into a byte array. But i've been asked to do that using InputStreamReader. So when i'm trying to open and read a pdf file for example using

File file = new File (inputFileName); 
Reader in = new
InputStreamReader(new FileInputStream(file)); 
char fileContent[] = new char[(int)file.length()]; 
in.read(fileContent); in.close();

and then save this content to another pdf file using

File outfile = new File(outputFile);
Writer out = new OutputStreamWriter(new FileOutputStream(outfile));
out.write(fileContent);
out.close();

Everything goes fine (no exception or errors) but when i'm trying to open the new file, either it says it's corrupted or wrond encoding.

Any suggestion??

ps1 i specifically need this using InputStreamReader

ps2 it works fine when trying to read/write .txt files

Answer

Joop Eggen picture Joop Eggen · Oct 9, 2014

String, char, Reader, Writer are for text in java. This text is Unicode, and hence all scripts may be combined.

byte[], InputStream, OutputStream is for binary data. If they represent text, they must be associated with some encoding.

The bridge between text and binary data always involves a conversion.

In your case:

Reader in = new InputStreamReader(new FileInputStream(file), encoding);
Reader in = new InputStreamReader(new FileInputStream(file)); // Platform's encoding

The second version is non-portable, as other computers can have any encodings.

In your case, do not use an InputStreamReader for binary data. The conversion can only corrupt things.

Maybe they intended to mean: do not read all in a byte array. In that case use a BufferedInputStream to read small byte arrays (a buffer) repeatedly.