java (Replace words) Suppose you have a lot of files in a directory that contain words Exercisei_j, where i and j are digits. Write a program that pads a 0 before i if i is a single digit and 0 before j if j is a single digit. For example, the word Exercise2_1 in a file will be replaced by Exercise02_01. 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_27 *
时间: 2024-03-10 19:48:36 浏览: 81
Sure, here's the Java code to accomplish the task:
```java
import java.io.File;
public class Exercise12_27 {
public static void main(String[] args) {
String[] files = args;
for (int i = 0; i < files.length; i++) {
if (files[i].startsWith("Exercise")) {
File file = new File(files[i]);
String filename = file.getName();
String[] parts = filename.split("_");
int iValue = Integer.parseInt(parts[0].substring(8));
int jValue = Integer.parseInt(parts[1].substring(0, parts[1].indexOf(".")));
String newFilename = "Exercise" + String.format("%02d", iValue) + "_" + String.format("%02d", jValue) + ".txt";
File newFile = new File(file.getParent(), newFilename);
file.renameTo(newFile);
}
}
}
}
```
This code takes the command line arguments as an array of strings, and loops through each argument. If the argument starts with "Exercise", it creates a `File` object for the file, and extracts the i and j values from the filename using string manipulation. It then creates a new filename with 0-padding for i and j values, and renames the file using the `renameTo()` method of the `File` class. You can run this program by saving it as a .java file and compiling it with `javac filename.java`, and then running it with `java Exercise12_27 *` in the directory with the files.
阅读全文