gpt4 book ai didi

java - 为什么不能在java中的用户生成的文件夹中创建子目录?

转载 作者:行者123 更新时间:2023-12-01 19:10:29 24 4
gpt4 key购买 nike

此代码生成一个文件夹,其输入名称由用户指定。创建了一个具有用户输入名称的目录,但我想要该目录内的子文件夹。我已经尝试了很多次,但始终无法创建,请帮助我。

import java.io.File;
import java.util.Scanner;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


public class Helper {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the project folder : ");
String proj_name = s.nextLine();
File f = new File("c:\\"+proj_name+"\\");
if (!f.exists()) {
if (f.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
}
}

最佳答案

根据我对您问题的理解,您希望从用户那里获取条目并一次性创建文件夹和子文件夹。您可以使用 file.mkdirs() 一次创建所有文件夹。

public class MakingADir {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the project folder : ");
String proj_name = s.nextLine();
System.out.println("Enter the sub-folder name : ");
String subFolder = s.nextLine();
String path = proj_name + File.separator + subFolder;
File f = new File("c:\\"+path+"\\");
if (!f.exists()) {
if (f.mkdirs()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
}
}

希望有帮助。

关于java - 为什么不能在java中的用户生成的文件夹中创建子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59488167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com