This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why do java have byte based and character based IO processing?  RSS feed

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In java i can perform I/O operations on file or socket with byte based or character based APIs.
such as fileReader (character based) or fileInputStream (byte based).

My point is what is the need of such distinction? Anyway a character is stored as a byte right?
 
Java Cowboy
Sheriff
Posts: 16083
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why: Because sometimes you want to read or write raw bytes from or to a file directly, and sometimes you want to interpret those bytes as text.

Anything in files, including characters, is ultimately stored as bytes. If you want to interpret bytes as characters, then you use a character encoding - that's what determines how the characters of a specific character set are represented as bytes. Character encodings can be quite complicated. ASCII is a very simple character encoding which uses exactly one byte (or actually, only 7 bits of a byte) to represent a character. UTF-8 is probably the most popular character encoding which encodes Unicode characters into variable length sequences (some characters are only one byte, some are two or even more bytes).

Java has streams (InputStream and OutputStream) to deal with bytes directly, and readers and writers, which are a layer on top of streams, to deal with text. It's just for convenience - it would be really cumbersome if there were only streams and you had to do all the character encoding and decoding yourself whenever you have to deal with text.
 
Manu Somasekhar
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jesper.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!