如何创建目录/文件夹?
一旦我测试了System.getProperty("user.home");
当且仅当新文件夹不存在时,我才必须创建一个目录(目录名称为“ new folder”)。
#1楼
您还可以引用makdir()函数在所需的文件夹中创建新目录。
#2楼
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
#3楼
虽然已经回答了这个问题。 我想添加一些额外的内容,即如果存在一个您要创建的目录名称的文件,它将提示错误。 对于未来的访客。
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
#4楼
使用此功能可以在用户主目录上创建目录。
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
#5楼
创建一个目录。new File("C:\\\\Directory1").mkdir();
一起创建一个名为“ Directory2”及其所有子目录“ Sub2”和“ Sub-Sub2”的目录。new File("C:\\\\Directory2\\\\Sub2\\\\Sub-Sub2").mkdirs()
资料来源:这个完美的教程 ,您还会发现一个使用示例。