2

I'm trying to make a simple program to copy file of any type. I write the code as below.

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

public class CopyExample {
  public static void main(String[] args) throws Exception {
    File f = new File("image.jpg");
    FileInputStream is = new FileInputStream(f);
    FileOutputStream os = new FileOutputStream("copy-image.png");
    byte[] ar = new byte[(int)f.length()];
    is.read(ar);
    os.write(ar);
    is.close();
    os.close();
  }
}

I already tested this code for .txt , .jpg , .png, .pdf It is working fine.

But I want to ask is it fine? or is there any other way to do this in better way?

2 Answers2

1

Copying a file is not about its file extension or type. It is about its content. If file is so big maybe computer's memory will not be enough.

Apache's FileUtils may be useful for your question.

this Q&A may help you.

And this article is about your question

Community
  • 1
  • 1
Yusuf K.
  • 4,195
  • 1
  • 33
  • 69
1

Java 7 provides Files class that you could use to copy a file

Files.copy(src,dest);
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24