How can I create a Folder using Java code on both Windows and Linux machines?
In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false.
Open the terminal application in Linux. The mkdir command is is used to create new directories or folders. Say you need to create a folder name dir1 in Linux, type: mkdir dir1.
File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These methods returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully.
new File("/path/to/folder").mkdir();
If you want to created nested folders (i.e. more than one folder on the path may be missing), then use mkdirs()
. See java.io.File
.
Note that forward slashes would normally not work on windows, but Java normalizes the path and translates forward to backward slashes.
try{
String strDirectoy ="test";
String strManyDirectories="dir1"+File.Separator+"dir2"+File.Separator+"dir3";
// Create one directory
boolean success = (new File(strDirectoy)).mkdir();
if (success) {
System.out.println("Directory: " + strDirectoy + " created");
}
// Create multiple directories
success = (new File(strManyDirectories)).mkdirs();
if (success) {
System.out.println("Directories: " + strManyDirectories + " created");
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Use File.mkdir() (http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdir())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With