Wednesday, April 8, 2020

[Java][Example] copy file

This is a simple method using FileInputStream and FileOutStream to copy file, you need to read the file content as bytes and use FileOutStream to write into a new file.

Remember import these package:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

Content:
try {
File sourceFile = new File("CCI29032020_2.jpg");
File newFile = new File("CCI29032020_2_new.jpg");
FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(newFile);
byte[] data = new byte[(int) sourceFile.length()];
fis.read(data);
fos.write(data);
fis.close();
fos.close();
}catch(IOException e) {
e.printStackTrace();
}

No comments :

Post a Comment