File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Copying data into a file using inputstream Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Copying data into a file using inputstream" Watch "Copying data into a file using inputstream" New topic

Copying data into a file using inputstream

A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 980

My input files has data..where each line is of different length

I am reading the file and copying the same into a different file.

But the problem is that ..after all the lines are written..there are additional values written to the file...

Pls check the program below...

Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
You are failing to take account of the return value from read(), where it tells you how many bytes were read. On the last read(), and possibly other times, that will be fewer than would fit in buf. You always write the whole of buf, so when fewer bytes were read, you write spurious stuff.

You should use the version of write() that takes a start and length value.

While I'm here, though, your code will be slow. A buffer of 48 bytes is much too small; a few thousand bytes would be more typical. Also, you should not flush() after every write. If you flush() at all, do it only after writing everything. In fact, close() will generally do an implicit flush() anyway.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Jan van Mansum
Ranch Hand

Joined: Oct 19, 2007
Posts: 74
Check the API for )] and )]FileOutputStream.write.

You will notice that read, reads up to b.length, so it may read less. However, write writes the full buffer, so if the previous read didn't fill the whole buffer, you will get garbage values in your output.

You need to check how much is actually read and then write exactly that amount to the output stream.

SCJP 1.4, SCWCD 1.4
I agree. Here's the link:
subject: Copying data into a file using inputstream
It's not a secret anymore!