(Rename files) Suppose you have a lot of files in a directory named Exercisei_j, where i and j are digits. Write a program that pads a 0 before i if i is a single digit. For example, a file named Exercise2_1 in a directory will be renamed to Exercise02_1. In Java, when you pass the symbol * from the command line, it refers to all files in the directory (see Supplement III.V). Use the following command to run your program: java Exercise12_28 *
时间: 2024-03-20 12:39:47 浏览: 20
Sure, here's a Java program that renames all files in the current directory that match the pattern "Exercisei_j" to "Exercise0i_j" if i is a single digit:
```java
import java.io.File;
public class Exercise12_28 {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java Exercise12_28 *");
return;
}
String pattern = "Exercise(\\d)_(\\d)";
for (String filename : args) {
if (filename.matches(pattern)) {
String newFilename = filename.replaceAll(pattern, "Exercise0$1_$2");
File file = new File(filename);
File newFile = new File(newFilename);
if (file.renameTo(newFile)) {
System.out.println(filename + " renamed to " + newFilename);
} else {
System.out.println("Error renaming " + filename);
}
}
}
}
}
```
To run this program, you can use the following command in the terminal (assuming the program is saved as Exercise12_28.java and has been compiled):
```
java Exercise12_28 *
```
This will run the program with all files in the current directory as arguments. The program will check each file name to see if it matches the pattern "Exercisei_j" and rename it if necessary. The new file name will be printed to the console for each renamed file.