6.练习

    技术2022-07-12  78

    6.练习_复制目录下所有文件

    学习:第7遍


    1.练习:复制目录下所有文件 复制指定目录"c:/aaa/old"下所有文件复制到"c:/aaa/new"


    public class Test{ //复制指定目录"c:/aaa/old"下所有文件复制到"c:/aaa/new" public static void main(String[] args) { String oldStr="c:/aaa/old"; String newStr="c:/aaa/new"; copyFile(oldStr,newStr); } /** * @方法名:copyFile(String oldStr, String newStr) * <方法功能描述>:目录下所有文件复制 */ private static void copyFile(String oldPath, String newPath) { File oldFile = new File(oldPath); File newFile = new File(newPath); if(oldFile.isDirectory()){ //新建目录 newFile=new File(newPath+File.separator+oldFile.getName()); newFile.mkdirs(); File[] listFiles = oldFile.listFiles(); for (File file : listFiles) { copyFile(file.getAbsolutePath(), newFile.getAbsolutePath()); } }else if(oldFile.isFile()){ //如果是文件,直接复制 try( FileInputStream fis = new FileInputStream(oldPath); FileOutputStream fos = new FileOutputStream(newPath+File.separator+oldFile.getName()); ){ int num=-1; byte[] buffer=new byte[1024]; while((num=fis.read(buffer))!=-1){ fos.write(buffer,0,num); } System.out.println("复制"+oldPath+"到"+newPath+"成功"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
    Processed: 0.012, SQL: 9