1. 程式人生 > >IO流中檔名批量修改和簡單複製剪下

IO流中檔名批量修改和簡單複製剪下

簡單利用IO流技術實現指定資料夾下,指定檔案型別的檔案進行重新命名,以及定義一個複製檔案的方法

如果要實現:

  1. 多級資料夾下的檔案修改或者複製,加上遞迴方法即可
  2. 檔名的修改,還可以利用字串的拼接​​​​​​​,subString,split,indexOf
public class FileNameChangeDemo1 {
    public static void main(String[] args) {
        File file1=new File("E:\\Java\\00_source\\demo1");
        //獲取當前路徑下的指定字尾名的 檔案 ;返回陣列
        File[] f=file1.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
               return new File(dir,name).isFile() && name.endsWith(".java");
            }
        });
        //遍歷:foreach或fori
        for (int i = 0; i < f.length; i++) {
            String name = f[i].getName();
            String newName = "0"+(i + 1) + ".jpg";
            System.out.println(newName);
            //保證路徑相同,重新命名,路徑不同是剪下並命名
            File file = new File("E:\\Java\\00_source\\demo2", newName);
            //修改後字尾名
            //name.replace(".jpg",".png");
            f[i].renameTo(file);
            //拓展需求:複製檔案
            //定義一個方法實現位元組流的輸入與輸出:copy
        }
    }
    //複製檔案
    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[] buffer = new byte[1024];
        int len ;
        while ((len = bis.read(buffer)) != -1){
            bos.write(buffer,0,len);
        }
        bos.close();
        bis.close();
    }
}