Tuesday, March 1, 2011

How to copy a file from one folder to another folder in Java

Assume that you want to copy the file "C:\\a.txt" to another location. Then you can use following method. 
You can easily change the name of the second file at the same time.
(Note that my first file is a.txt and the name of the new file is b.txt)

try {
  String path1 = "C:\\a.txt";
  String path2 = "D:\\b.txt";
  File file1 = new File(path1);
  File file2 = new File(path2);
  FileInputStream fis = new FileInputStream(file1);
  FileOutputStream fos = new FileOutputStream(file2);
  byte[] byteArray = new byte[1024];
  int i = 0;
  while((i = fis.read(byteArray) )!= -1) {
    fos.write(byteArray, 0, i);
  }
  fis.close();
  fos.close();
} catch (Exception e) {
  e.printStackTrace();
}

No comments:

Post a Comment