Zo72
Zo72

Reputation: 15305

Java: Most efficient way to read from inputStream and write to an outputStream (plus a few modifications)

I am reading from an InputStream. and writing what I read into an outputStream.

I also check a few things. Like if I read an

& (ampersand)

I need to write

"& amp;"

My code works. But now I wonder if I have written the most efficient way (which I doubt).

I read byte by byte. (but this is because I need to do odd modifications)

Can somebody who's done this suggest the fastest way ?

Thanks

Upvotes: 1

Views: 3055

Answers (3)

jayantS
jayantS

Reputation: 837

I would prefer to use BufferedReader for reading input and BufferedWriter for output. Using Regular Expressions for matching your input can make your code short and also improve your time complexity.

Upvotes: 1

BillRobertson42
BillRobertson42

Reputation: 12883

The code should be reading/writing characters with Readers and Writers. For example, if its in the middle of a UTF-8 sequence, or it gets the second half of a UCS-2 character and it happens to read the equivalent byte value of an ampersand, then its going to damage the data that its attempting to copy. Code usually lives longer than you would expect it to, and somebody might try to pick it up later and use it in a situation where this could really matter.

As far as being faster or slower, using a BufferedReader will probably help the most. If you're writing to the file system, a BufferedWriter won't make much of a difference, because the operating system will buffer writes for you and it does a good job. If you're writing to a StringWriter, then buffering will make no difference (may even make it slower), but otherwise buffering your writes ought to help.

You could rewrite it to process arrays; and that might make it faster. You can still do that with arrays. You will have to write more complicated code to handle boundary conditions. That also needs to be a factor in the decision.

Measure, don't guess, and be wary of opinions from people who aren't informed of all the details. Ultimately, its up to you ot figure out if its fast enough for this situation. There is no single answer, because all situations are different.

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

If you are using BufferedInputStream and BufferedOutputStream then it is hard to make it faster.

BTW if you are processing the input as characters as opposed to bytes, you should use readers/writers with BufferedReader and BufferedWriter.

Upvotes: 5

Related Questions