• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Copying data into a file using inputstream

 
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

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...

 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check the API for )]FileInputStream.read 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic