Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a New folder using Java Program on Windows and Linux machines

How can I create a Folder using Java code on both Windows and Linux machines?

like image 435
Puru Avatar asked Dec 13 '10 09:12

Puru


People also ask

How do you create a new directory in Java?

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​.

How do you create a folder with Linux?

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.

How do you create a file and directory in Java?

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.


3 Answers

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.

like image 134
Bozho Avatar answered Oct 19 '22 16:10

Bozho


 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());
    }  
  • Document
like image 20
jmj Avatar answered Oct 19 '22 15:10

jmj


Use File.mkdir() (http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdir())

like image 23
thoredge Avatar answered Oct 19 '22 16:10

thoredge