How to Create a Folder in Java

How to create a directory in Java?

After ~7 year, I will update it to better approach which is suggested by Bozho.

File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}

How to create a new folder under given path using Java?

Working code Example : Following your approach

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FolderDemo {

public static void writeRequestAndResponse() {

Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");

String currentDateTime = format.format(date);

String folderPath = "F:\\working\\POC\\Output\\" + "LastRunOn_"
+ currentDateTime;

File theDir = new File(folderPath);

// if the directory does not exist, create it
if (!theDir.exists()) {
System.out.println("creating directory: " + theDir.getName());
boolean result = false;

try {

theDir.mkdirs();
result = true;
} catch (SecurityException se) {
// handle it
System.out.println(se.getMessage());
}
if (result) {
System.out.println("Folder created");
}
} else if (theDir.exists()) {

System.out.println("Folder exist");
}

}

public static void main(String[] args) {
writeRequestAndResponse();
}

}

Few things to remember :

  1. File or folder names cannot contain any of the following characters:\, /, :,

*, ?, "", <, >, |.

That is why your Time format "yyyy_MM_dd_HH:mm:ss" was not added to the folder name.

So I replaced " : " with " . "

How to create directory in Java :

To create a directory in Java, uses the following code:

  1. Standard Java IO package – java.io.File

1.1 Create a single directory.

new File("C:\Directory1").mkdir();

1.2 Create a directory named “Directory2 and all its sub-directories “Sub2” and “Sub-Sub2” together.

new File("C:\Directory2\Sub2\Sub-Sub2").mkdirs()

Both method mkdir() and mkdirs() are returning a boolean value to indicate the operation status : true if succeed, false otherwise.

How to create a folder in Java?

File f = new File("C:\\TEST");
try{
if(f.mkdir()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
} catch(Exception e){
e.printStackTrace();
}

Create a directory if it does not exist and then create the files in that directory as well

This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.

Also, I replaced your append calls with concat or + as I saw appropriate.

public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";

File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}

File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}

You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.

Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}

Creating new folders in java with dynamic naming

Use recursive method , if Folder already exists this will create new folder using counter

int count;

public void createFolder() {
File file = new File("C:\\Users\\user\\Desktop\\new\\"" + count);
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
count++;
}
} else {
System.out.println("Failed to create directory!");
count++;
createFolder();
}
}

To create a new directory and a file within it using Java

Basically, what's happening is, you are creating a directory called Library\test.txt, then trying to create a new file called the same thing, this obviously isn't going to work.

So, instead of...

File file = new File("Library\\test.txt");
file.mkdir();
file.createNewFile();

Try...

File file = new File("Library\\test.txt");
file.getParentFile().mkdir();
file.createNewFile();

Additional

mkdir will not actually throw any kind of exception if it fails, which is rather annoying, so instead, I would do something more like...

File file = new File("Library\\test.txt");
if (file.getParentFile().mkdir()) {
file.createNewFile();
} else {
throw new IOException("Failed to create directory " + file.getParent());
}

Just so I knew what the actual problem was...

Additional

The creation of the directory (in this context) will be at the location you ran the program from...

For example, you run the program from C:\MyAwesomJavaProjects\FileTest, the Library directory will be created in this directory (ie C:\MyAwesomJavaProjects\FileTest\Library). Getting it created in the same location as your .java file is generally not a good idea, as your application may actually be bundled into a Jar later on.

creating folders for all users

try using the following:

String userName = System.getProperty("user.name"); //platform independent 
File f = new File ("/Users/" + userName + "/Desktop/nameOfDir");
f.mkdirs();

Create file in Java with all parent folders

You can ensure that parent directories exist by using this method File#mkdirs().

File f = new File("D:\\test3\\ts435\\te\\util.log");
f.getParentFile().mkdirs();
// ...

If parent directories don't exist then it will create them.



Related Topics



Leave a reply



Submit