JAVA FILE or I/O学习 - 补充CopyFiles功能
1 public class CopyFiles 2 { 3 public static void main(String[] args) 4 { 5 CopyFiles copyFiles = new CopyFiles(); 6 copyFiles.copyS("E:\\", "【 图 片 】", "E:\\cba"); 7 } 8 public void copyS(String sourcePath,String name,String newPath) 9 { 10 File file = new File(sourcePath, name); 11 if (file.isDirectory()) 12 { 13 //在新位置创建该文件夹 14 File fileDir = new File(newPath, name); 15 if (!fileDir.exists()) 16 { 17 fileDir.mkdir(); 18 System.out.println("复制文件夹:"+fileDir); 19 } 20 else { 21 JOptionPane.showMessageDialog(null, "新路径中已经存在该文件!\n"+fileDir, "复制文件 - 提示", JOptionPane.WARNING_MESSAGE); 22 return; 23 } 24 25 //操作原位置文件夹中的文件、文件夹 26 File[] nextFiles = file.listFiles(); 27 if (nextFiles.length == 0) 28 { 29 return; 30 } 31 else { 32 for (File fileNext : nextFiles) 33 { 34 copyS(file.getAbsolutePath(), fileNext.getName(), fileDir.getAbsolutePath()); 35 } 36 } 37 } 38 else { 39 //复制文件 40 byte[] data = new byte[1024]; 41 try 42 { 43 BufferedInputStream input = new BufferedInputStream(new FileInputStream(file)); 44 File fileNew = new File(newPath, name); 45 if (fileNew.exists()) 46 { 47 JOptionPane.showMessageDialog(null, "新路径中已经存在该文件!\n"+fileNew, "复制文件 - 提示", JOptionPane.WARNING_MESSAGE); 48 return; 49 } 50 fileNew.createNewFile(); 51 System.out.println("复制文件:"+fileNew); 52 BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(fileNew)); 53 while (input.read(data) != -1) 54 { 55 output.write(data); 56 } 57 output.flush(); 58 output.close(); 59 input.close(); 60 } catch (FileNotFoundException e) 61 { 62 // TODO Auto-generated catch block 63 e.printStackTrace(); 64 } catch (IOException e) 65 { 66 // TODO Auto-generated catch block 67 e.printStackTrace(); 68 } 69 } 70 } 71 }