ต่อไปนี้เป็นรหัสเพื่อเปลี่ยนชื่อหลายไฟล์โดยใช้ Java -
ตัวอย่าง
import java.io.File;
import java.io.IOException;
public class Demo{
public static void main(String[] argv) throws IOException{
String path_to_folder = "path\\to\\folder\\where\\multiple\\files\\are\\present";
File my_folder = new File(path_to_folder);
File[] array_file = my_folder.listFiles();
for (int i = 0; i < array_file.length; i++){
if (array_file[i].isFile()){
File my_file = new File(path_to_folder + "\\" + array_file[i].getName());
String long_file_name = array_file[i].getName();
String[] my_token = long_file_name.split("\\s");
String new_file = my_token[1];
System.out.println(long_file_name);
System.out.print(new_file);
my_file.renameTo(new File(path_to_folder + "\\" + new_file + ".pdf"));
}
}
}
} ผลลัพธ์
The files in the folder will be renamed to .pdf
คลาสชื่อ Demo มีฟังก์ชันหลัก โดยที่ apth ไปยังโฟลเดอร์ที่มีหลายไฟล์ถูกกำหนดไว้ โฟลเดอร์ใหม่ถูกสร้างขึ้นในเส้นทางที่กล่าวถึง
รายการไฟล์ได้มาจากฟังก์ชัน 'listFiles' ไฟล์ของอาร์เรย์ถูกวนซ้ำ และหากพบไฟล์ จะมีการสร้างพาธไฟล์ใหม่และได้รับชื่อไฟล์และแยกไฟล์นั้นออก ไฟล์ถูกเปลี่ยนชื่อเป็น .pdf ชื่อของไฟล์จะสั้นลงโดยได้รับสตริงย่อยที่เริ่มต้นหลังจากเว้นวรรคแรกใน 'long_file_name'