• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Manu Somasekhar
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?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!