(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-21 08:41:28 浏览: 63
FileReadWrite with text aread output.zip_In Writing_file readers
Sure, I can help you write a program in Java that renames the files in the directory as per your requirements. Here's the code:
```java
import java.io.File;
public class Exercise12_28 {
public static void main(String[] args) {
String directory = ".";
String pattern = "Exercise\\d_[\\d]+";
if (args.length > 0) {
directory = args[0];
}
File dir = new File(directory);
if (!dir.isDirectory()) {
System.out.println("Error: Invalid directory");
return;
}
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile() && file.getName().matches(pattern)) {
String oldName = file.getName();
String[] parts = oldName.split("_");
String newName = "Exercise" + String.format("%02d", Integer.parseInt(parts[0].substring(8))) + "_" + parts[1];
File newFile = new File(dir.getAbsolutePath() + "\\" + newName);
boolean success = file.renameTo(newFile);
if (!success) {
System.out.println("Error: Could not rename file " + oldName);
}
}
}
System.out.println("Successfully renamed files");
}
}
```
This program takes an optional argument, which is the directory containing the files. If no argument is provided, it defaults to the current directory. It then looks for files in the directory that match the pattern "Exercisei_j", where i and j are one or more digits. For each such file, it extracts the digits i and j from the filename, pads a 0 before i if i is a single digit, and constructs a new filename in the format "Exerciseii_j". It then renames the file to the new name.
To run this program, you can use the following command:
```
java Exercise12_28 *
```
This will rename all files in the current directory that match the pattern "Exercisei_j". Note that the "*" symbol is used to pass all files in the directory as arguments to the program.
阅读全文