1.1.1 Copy a single-level folder
/*
* Data source: e:\\demo
* Destination: e:\\test
*
* analyze:
* A: Package directory
* B: Get the File array of all texts in this directory
* C: Traverse the File array to get each File object
* D: Copy the file
*/
public class CopyFolderDemo {
public static void main(String[] args) throws IOException {
// package directory
File srcFolder = new File("e:\\demo");
// encapsulate the destination
File destFolder = new File("e:\\test");
// If the destination folder does not exist, create it
if (!destFolder.exists()) {
destFolder.mkdir();
}
// Get the File array of all texts in this directory
File[] fileArray = srcFolder.listFiles();
// Traverse the File array to get each File object
for (File file : fileArray) {
// System.out.println(file);
// Number source: e: \\ demo \\ e.mp3
// destination: e:\\test\\e.mp3
String name = file.getName(); // e.mp3
File newFile = new File(destFolder, name); // e:\\test\\e.mp3
copyFile(file, newFile);
}
}
private static void copyFile(File file, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte [] bys = new byte [1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}