• Post Reply Bookmark Topic Watch Topic
  • New Topic

binary files and char []  RSS feed

 
M Berg
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi experts,

what's there with binary files (*.jpg, *.pdf, etc) that can be handled with byte[] arrays but not with char[] arrays?

Should I get FileReader & FileWriter (Java recommendation) working with binary files at all?

Many thanks,
Kind regards MB
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always thought FileReader and FileWriter were intended for text files. Similarly char[] arrays are intended for text.

I presume you are familiar with the appropriate part of the Java™ Tutorials? Look at the sections about Object streams and data streams and byte streams. See whether they help.
 
Alex Hurtt
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In java.io, Readers/Writers are for text and InputStream/OutputStream are for binary data. There are also 2 classes, the InputStreamReader and OutputStreamWriter which are for bridging between byte streams and character data using specified character set encodings.

Part of the problem you can run into with using bytes when you should be using chars is that it only works for basic ASCII encoding. In java a byte is a signed 8 bit integer type which can represent numbers between -128 and 127 inclusive. A char in java is an unsigned 16 bit type. It can represent many more character encodings other than the basic 128 basic ASCII. If your text file is UTF-8 encoded text lets say...and it contains non-ASCII characters, those aren't going to be represented correctly using a byte[] because a byte is unaware of character encoding. Your 16 bit long UTF-8 characters will come out looking like 2 separate 8 bit values which may or may not correspond to printable ascii characters.

I would say working with binary file types like .jpg, .pdf, etc...you want to be using FileInputStream/FileOutputStream, not FileReader/FileWriter.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!