Copying a file with java using Input/Output Stream

Description:

The piece of code below shows you how to copy two files using Java. We're going to use basic java classes, mainly they are: FileInputStream and FileOutputStream.


Solution:

package com.javaproblems.binaryfiles;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BinaryFileCopy {

 
 public static void main(String[] args) {
  try {
   File f1 = new File("MyPhoto.jpg");
   File f2 = new File("TrgtMyPhoto.jpg");
   
   FileInputStream in = new FileInputStream(f1);
   FileOutputStream out = new FileOutputStream(f2);
   
   byte[] buf = new byte[1024];
   int len;
   
   while ((len=in.read(buf)) > 0) {
    out.write(buf, 0, len);
   }
   
   in.close();
   out.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  

 }

}



No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact