aspose file tools
The moose likes Beginning Java and the fly likes binary files and char [] Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "binary files and char []" Watch "binary files and char []" New topic
Author

binary files and char []

M Berg
Greenhorn

Joined: Sep 01, 2010
Posts: 13
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
Sheriff

Joined: Oct 13, 2005
Posts: 32654
    
    4
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

Joined: Oct 26, 2010
Posts: 98
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: binary files and char []
 
Similar Threads
I/O Eating Data
Problem in wrtitng JAR File
Best way to read large Binary Files
serializing large object (hashmap)
ANT FTP download new line problem.