• 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 files corrupts file

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

Have a little problem copying files using Java...

I can copy the file OK, and all appears well, until you try to open the file. Then no matter what the file type (although mine are primarily images) you get the following error:-

XXX can not read this file
This is not a valid XXX file or it's format is not curremtly supported


Here is my code (Note the DestinationFolder, DestinationFile, SourceFile etc are all valid, i just haven't showed how they are parsed as it is too long):-

DestinationFolder.mkdir();
Destination.createNewFile();
InputStream input = new FileInputStream(SourceFile);
OutputStream output = new FileOutputStream(DestinationFile);
byte[] buffer = new byte[1024];
int length = input.read();
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
input.close();
output.close();
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Right here,

int length = input.read();

you read the first byte of the file and discard it. If you replace this with just

int length;

you should be golden.
 
Kevin P Smith
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am now offically golden in colour! Cheers :-D
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic