Implement folder traversal and replication
1. Folder traversal
public static void ergodic(String path){ File file = new File(path); for (File one : file.listFiles()) { System.out.println("Route:" + one.getPath()); System.out.println("Type:" + one.isDirectory()); // If it is a folder, continue to get the contents under the subfolder if (one.isDirectory()) { for (File f : one.listFiles()) { System.out.println("=Route:" + f.getPath()); // Check if there is Directory, and continue to get. listFiles() } } } }
This method uses the idea of recursion.
2. Folder copy
1. First, copy the file. There are two methods, character stream and byte stream
Copy with character stream first
/** * This method can copy files * @param path1 Files to be copied * @param path2 Address to which files are copied */ public static void copy1(String path1, String path2){ FileReader fr; FileWriter fw; try { fr = new FileReader(path1); try{ fw = new FileWriter(path2); char [] c = new char [30]; int n = 0; while (-1 != (n = fr.read(c))){ fw.write(c, 0 ,n); } fw.close(); fr.close(); }catch(IOException e){ e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
2. Copy with byte stream
/** * This method can copy files * @param path1 Files to be copied * @param path2 Address to which files are copied */ public static void copy2(String path1, String path2){ try{ FileInputStream fileReader = new FileInputStream(path1); try{ FileOutputStream fileWriter = new FileOutputStream(path2); int n = 0; byte [] b = new byte [30]; while (-1 != (n = fileReader.read(b))){ fileWriter.write(b, 0, n); } fileWriter.close(); fileReader.close(); }catch(IOException e){ e.printStackTrace(); } }catch(FileNotFoundException e){ e.printStackTrace(); } }
Note: character stream can only be copied to. txt file. Other formats need to be copied by byte stream.
3. In the end, the idea of recursion is used to copy folders. In essence, recursion is used to traverse folders and copy files when they are encountered
/** * This method realizes the replication of folders * @param path1 Folders to copy * @param path2 Address to which the folder is copied */ public static void copy3(String path1, String path2){ File f1 = new File(path2); // Get the current file or directory of the source folder File file = new File(path1); if (file.isFile()) { // Copy files. copy2 is the method to copy files above copy2(file.getAbsolutePath(), path2); System.out.println("sssssssssss"); } else if (file.isDirectory()) { f1.mkdirs(); for (File f : file.listFiles()){ String path = path2+"\\" + f.getName(); System.out.println("------------"); // Recursion, calling itself copy3(f.getAbsolutePath(), path); } } }