Sanyam Goel
Sanyam Goel

Reputation: 2180

Why should IO as Byte be avoided in Java

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. It has been mentioned that there are streams for characters ,objects etc that should be preferred although all are built on the bytestream itself. What is a reason behind this, has it anything to do with security manager and performance related issues?

source : oracle docs

Upvotes: 1

Views: 95

Answers (3)

Thilo
Thilo

Reputation: 262684

From the text you quoted:

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since xanadu.txt contains character data, the best approach is to use character streams, as discussed in the next section. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O.

Usually, you don't want to work with bytes directly. There are higher-level APIs, for example to read text (i.e. character data that has to be decoded from bytes).

Upvotes: 3

parasietje
parasietje

Reputation: 1539

What Oracle is actually saying, is "Please do not reimplement the wheel!".

You should almost never need regular Byte streams:

  • Are you parsing text? Use a Character stream, which understand text encoding issues.
  • Are you parsing XML? Use SAX or some other library.
  • Are you parsing images? Use ImageIO class.
  • Are you copying things from A to B? Use apache commons-io FileUtils.

There are very few situations where you will actually need to use the bytestream.

Upvotes: 4

Joachim Sauer
Joachim Sauer

Reputation: 308121

It works, but is very inefficient: it needs 2 method calls for every single byte it copies.

Instead, you should use a buffer (of several thousand bytes, the best size varies by what exactly you read and other conditions) and read/write the entire buffer (or as much as possible) with every method call.

Upvotes: 2

Related Questions