背景:公司要求使用PADS完成原理图设计、PCB Layout。而他硬件工程师要求我在将PADS的库文件发送给他们之前,必须在每一个库文件的后面追加今天的日期,再发送给他们。
问题来了,如果一次需要发送多个库文件,那我就得修改很多个库文件的名字,这个过程十分繁琐枯燥、费时费力。
于是,我想:能不能使用Java语言设计一个程序,用于批量修改某个文件夹里面的文件的名字呢?
答案是肯定的。于是,趁着今天周末有空,动动脑子和手,解决这些问题。
修改前的文件名:
程序
1 import java.io.File; 2 import java.text.DateFormat; 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 public class IOFileTest { 7 8 public static void main(String[] args) { 9 // 日期格式,例如:2019033110 DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");11 12 // 指定路径13 File filepath = new File("E:/PADS/Libraries/temp");14 15 // 列出该路径下所有文件16 File[] originalfiles = filepath.listFiles();17 for (int i = 0; i < originalfiles.length; i++) {18 System.out.println(dateFormat.format(new Date()));19 20 // 获取父目录21 String parentDirectory = originalfiles[i].getParent();22 23 StringBuilder stringBuilder = new StringBuilder(originalfiles[i].getName());24 // 搜索".",因为"."之后文件的后缀名,将要追加的字符串是添加在后缀名前面的25 int index = stringBuilder.lastIndexOf(".");26 // 在后缀名前面插入今天的日期27 stringBuilder.insert(index, "_" + dateFormat.format(new Date()));28 29 // 重命名文件30 File newFile = new File(parentDirectory + File.separator + stringBuilder);31 if (originalfiles[i].renameTo(newFile)) {32 System.out.println("The original file is " + originalfiles[i].getName());33 System.out.println("The new file is " + newFile.getName());34 System.out.println();35 } else {36 System.out.println("Fail!");37 }38 }39 }40 }
运行结果(修改后的文件名):
例2:基于JavaFX实现UI界面:
1 import java.io.File; 2 import java.text.DateFormat; 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 import javafx.animation.KeyFrame; 7 import javafx.animation.Timeline; 8 import javafx.application.Application; 9 import javafx.event.ActionEvent; 10 import javafx.event.EventHandler; 11 import javafx.geometry.Insets; 12 import javafx.geometry.Pos; 13 import javafx.scene.Scene; 14 import javafx.scene.control.Button; 15 import javafx.scene.control.Label; 16 import javafx.scene.control.TextField; 17 import javafx.scene.control.Tooltip; 18 import javafx.scene.layout.GridPane; 19 import javafx.stage.DirectoryChooser; 20 import javafx.util.Duration; 21 import javafx.stage.Stage; 22 23 public class Main extends Application { 24 File directory = null; 25 26 public static void main(String[] args) { 27 launch(args); 28 } 29 30 @Override 31 public void start(Stage primaryStage) throws Exception { 32 // Create a pane to hold a button 33 GridPane pane = new GridPane(); 34 pane.setStyle("-fx-border-color: green;"); 35 pane.setAlignment(Pos.CENTER); 36 pane.setPadding(new Insets(10, 10, 10, 10)); 37 pane.setHgap(10); 38 pane.setVgap(10); 39 40 // Label 41 Label labelInformation = new Label("Waiting..."); 42 43 // Text Field 44 TextField tfDirectory = new TextField(); 45 tfDirectory.setPrefColumnCount(40); 46 tfDirectory.setTooltip(new Tooltip("Select a directory.")); 47 48 // Create a button to choose a directory 49 Button btChooseDirectory = new Button("Choose Folder"); 50 51 // Create a button to start... 52 Button btStartTranslation = new Button("Start Modify"); 53 54 // Add all node to the pane. 55 pane.add(tfDirectory, 0, 0); 56 pane.add(btChooseDirectory, 1, 0); 57 pane.add(labelInformation, 0, 1); 58 pane.add(btStartTranslation, 1, 1); 59 60 // Set the date format 61 DateFormat df = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss"); 62 // Update the time 63 Timeline animation = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler() { 64 @Override 65 public void handle(ActionEvent event) { 66 primaryStage.setTitle("Rename File " + df.format(new Date())); 67 } 68 })); 69 animation.setCycleCount(Timeline.INDEFINITE); 70 animation.play(); 71 72 // Set the primary stage properties 73 primaryStage.setScene(new Scene(pane)); 74 primaryStage.setTitle("Rename File " + df.format(new Date())); 75 primaryStage.setResizable(false); 76 primaryStage.show(); 77 78 // Event Handler 79 btChooseDirectory.setOnAction(new EventHandler () { 80 @Override 81 public void handle(ActionEvent event) { 82 DirectoryChooser directoryChooser = new DirectoryChooser(); 83 directoryChooser.setTitle("Choose Folder"); 84 directory = directoryChooser.showDialog(new Stage()); 85 if (directory != null) { 86 tfDirectory.setText(directory.getAbsolutePath()); 87 System.out.println(directory.getAbsolutePath()); 88 } 89 } 90 }); 91 92 btStartTranslation.setOnAction(new EventHandler () { 93 @Override 94 public void handle(ActionEvent event) { 95 if (directory != null) { 96 labelInformation.setText("Start renaming all files..."); 97 System.out.println("Start renaming all files..."); 98 long t1 = System.currentTimeMillis(); 99 // Date format100 DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmm");101 // List out all files in the directory102 File[] originalfiles = directory.listFiles();103 for (int i = 0; i < originalfiles.length; i++) {104 // List the files which with extension ".ld9", ".ln9", ".pd9", ".pt9"105 if ((originalfiles[i].getName().endsWith(".ld9"))106 | (originalfiles[i].getName().endsWith(".ln9"))107 | (originalfiles[i].getName().endsWith(".pd9"))108 | (originalfiles[i].getName().endsWith(".pt9"))) {109 StringBuilder stringBuilder = new StringBuilder(originalfiles[i].getName());110 stringBuilder.insert(stringBuilder.lastIndexOf("."), "_" + dateFormat.format(new Date()));111 112 // Rename files113 File newFileName = new File(directory.getAbsolutePath() + File.separator + stringBuilder);114 if (originalfiles[i].renameTo(newFileName)) {115 System.out.println("The original file name is " + originalfiles[i].getName());116 System.out.println("The new file name is " + newFileName.getName());117 System.out.println();118 } else {119 System.out.println("Failed to rename " + originalfiles[i].getName());120 }121 }122 }123 long t2 = System.currentTimeMillis();124 labelInformation.setText("Rename completed. Elapsed time: " + (t2 - t1) + " ms");125 System.out.println("Rename completed. Elapsed time: " + (t2 - t1) + " ms");126 } else {127 labelInformation.setText("Please choose a directory first.");128 System.out.println("Please choose a directory first.");129 }130 }131 });132 }133 }