(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 19:41:44 浏览: 198
Sure, I can help you with that. Here is a Java program that renames all the files in the directory with a single-digit number padded with a zero:
```java
import java.io.File;
public class Exercise12_28 {
public static void main(String[] args) {
String pattern = "(Exercise)(\\d)_(\\d)";
String replace = "Exercise0$2_$3";
for (String filename : args) {
File file = new File(filename);
if (file.isFile() && file.getName().matches(pattern)) {
String newname = file.getName().replaceAll(pattern, replace);
file.renameTo(new File(file.getParent(), newname));
System.out.println("Renamed " + filename + " to " + newname);
}
}
}
}
```
To run this program, you can save it in a file named `Exercise12_28.java` and then compile and run it from the command line:
```
$ javac Exercise12_28.java
$ java Exercise12_28 *
```
This will rename all the files in the current directory that match the pattern `Exercisei_j` to `Exercise0i_j`. The program uses regular expressions to match the filenames and replace the single-digit number with a zero-padded version. The `File` class is used to rename the files.
阅读全文