要求用户输入一个目录名并使用File在当前目录下创建出来。 若该目录已经存在则提示用户该目录已经存在。并创建副本原则与第二题一致。
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入目录名:");
String dirName = scanner.nextLine();
File dir = new File(dirName);
if (dir.exists()) {
System.out.println("该目录已经存在,将创建副本。");
int count = 1;
while (true) {
String newDirName = dirName + "_" + count;
File newDir = new File(newDirName);
if (!newDir.exists()) {
dir = newDir;
break;
}
count++;
}
}
boolean success = dir.mkdirs();
if (success) {
System.out.println("目录创建成功:" + dir.getAbsolutePath());
} else {
System.out.println("目录创建失败。");
}
}
}
``
原文地址: https://www.cveoy.top/t/topic/huNR 著作权归作者所有。请勿转载和采集!