如何创建目录/文件夹?
一旦我测试了System.getProperty("user.home");
我必须创建一个目录(目录名“新文件夹”)当且仅当新文件夹不存在时。
如何创建目录/文件夹?
一旦我测试了System.getProperty("user.home");
我必须创建一个目录(目录名“新文件夹”)当且仅当新文件夹不存在时。
当前回答
虽然这个问题已经有了答案。我想多放点东西,比如。 如果存在与您试图创建的目录名称相同的文件,则会提示错误。为将来的访客准备的。
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");
}
}
}
其他回答
该功能允许在用户的主目录上创建新目录。
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");
}
}
对于java 7及以上版本:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
在创建之前检查目录或文件是否存在似乎是不必要的,from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored. If this method fails, then it may do so after creating some, but not all, of the parent directories.
虽然这个问题已经有了答案。我想多放点东西,比如。 如果存在与您试图创建的目录名称相同的文件,则会提示错误。为将来的访客准备的。
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");
}
}
}
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();
}
}
}
在Java 7中,您可以使用Files.createDirectories()。
例如:
Files.createDirectories(Paths.get("/path/to/directory"));