利用Java實現指定文件夾下的照片以自定義格式移動

  • 2020 年 3 月 12 日
  • 筆記

前幾天本猿的大學同學,一個漂亮的小姐姐工作時遇到了一個問題,她的需求是,在公司區域網的電腦上下載大量的圖片重命名成指定得1、2、3…..以此類推,需要當天完成,我就臨時給寫了一個小demo。

我的想法是採用linux的原理不就好實現嗎,直接mv到指定文件夾下再給一個新的名字不就實現了嗎

我給出的程式碼如下(不是很成熟,還請大佬們多多指教):

 1 public class FileRename {   2     public static void main(String[] args) throws Exception {   3         Integer n = Integer.valueOf(args[0]);   4         String src = args[1];   5         String dest = args[2];   6         for (int i = 1; i <= n; i++){   7             String name2 =" ("+i+")"+".png";   8             String newName = src +name2;   9             System.out.println("success:"+newName);  10             File afile=new File(newName);  11             FileInputStream fis = new FileInputStream(afile);  12             FileOutputStream fos = new FileOutputStream(new File(dest+i+".png"));  13             byte[] read = new byte[1024];  14             int len = 0;  15             while((len = fis.read(read))!= -1){  16                 fos.write(read,0,len);  17             }  18             fis.close();  19             fos.flush();  20             fos.close();  21  22         }  23  24     }  25  26 }

因為她沒有IDE所以參數都改成傳參
args[0]是需要改名的文件數
args[1]是原路徑
args[2]是目標路徑
剩下的就javac編譯 java + 參數運行就可以了
此方式簡陋但是也還算實用

重命名的方法也試過了但是不符合要求所以出此下策