In: Computer Science
Java Chapter 12.29 (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 j if j is a single digit. For example, a file named Exercise2_1 in a directory will be renamed to Exercise2_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_29 * can you make a example directory with sample files.. Please type you answer. Thanks
RenameFiles.java:
import java.io.File;
public class RenameFiles {
public static void main(String[] args) {
if(args.length != 0) {
for(String name: args) {
File f = new File(name);
if(f.isFile()){
String newName = getNewName(f.getName());
if(newName != null) {
File newFile = new
File(newName);
f.renameTo(newFile);
}
}
}
}
}
private static String getNewName(String name)
{
String tokens[] =
name.split("_");
// if string is ending on _ without
any digit at last
if(name.charAt(name.length()-1) ==
'_') {
return
null;
}
// if string has got _ then, there
will be atleast two parts
if(tokens.length >= 2) {
String fullName
= "";
int i=0;
while(i <
tokens.length-1) {
fullName += tokens[i] + "_";
i++;
}
// if last token
is single digit
if(tokens[tokens.length - 1].length()==1) {
if(Character.isDigit(tokens[tokens.length -
1].charAt(0))) {
fullName += "0" +
tokens[tokens.length-1];
return fullName;
} else
return null;
} else
return null;
}
return null;
}
}
Sample Output:
Program can be run as : java RenameFiles * as
shown in the above image. It changes the files names as
expected.