Copy the Java implementation file or folder to the specified directory instance
- 2020-06-15 09:05:39
- OfStack
Sort out the documents, search out 1 Java implementation file or folder copy to the specified directory code, sort out a little 1 to share.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Test {
private static int a = 5;
public static void main(String[] args) {
// The destination file or destination folder that needs to be copied
String pathname = "C:/Users/likun/Desktop/git_project";
File file = new File(pathname);
// Copy to
String topathname = "C:/Users/likun/Desktop/movie";
File toFile = new File(topathname);
try {
copy(file, toFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void copy(File file, File toFile) throws Exception {
byte[] b = new byte[1024];
int a;
FileInputStream fis;
FileOutputStream fos;
if (file.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath=filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath=toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());
File copy=new File(toFilepath);
// Copy folders
if (!copy.exists()) {
copy.mkdir();
}
// Traversal folder
for (File f : file.listFiles()) {
copy(f, copy);
}
} else {
if (toFile.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath=filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath=toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());
// Write files
File newFile = new File(toFilepath);
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
} else {
// Write files
fis = new FileInputStream(file);
fos = new FileOutputStream(toFile);
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
}
}
}
}