Friday, September 23, 2011

Welcome - How to copy files in Java

Welcome to my site. This is the first post and I want to write how to copy files in Java.


We need a source file and a destination file:
File source = new File("source.mp3");
File destination = new File("destination.mp3");
Next, we have to create an input stream and an output stream, reading the input file and writing in the output file. This is the code:
try {
 InputStream in = new FileInputStream(source);
 OutputStream out = new FileOutputStream(destination);

 // to read while data exist in the input stream
 byte[] buf = new byte[1024];
 int len;

 while ((len = in.read(buf)) > 0) {
  out.write(buf, 0, len);
 }

 // to close opened files
 in.close();
 out.close();

 } 
 catch (FileNotFoundException e1) {
  e1.printStackTrace();
 }
 catch (IOException e2) {
  e2.printStackTrace();
 }
}
I hope you like this and I've helped, Regards!

No comments:

Post a Comment