- How to Create a Folder in Java
- How to create a new folder under given path using Java?
- How to create a folder in Java?
- Create a directory if it does not exist and then create the files in that directory as well
- How to create empty folder in java?
- Creating new folders in java with dynamic naming
- To create a new directory and a file within it using Java
- creating folders for all users
- Create file in Java with all parent folders
- Creating new folder in java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Creating and Reading Directories
- Listing a File System’s Root Directories
- Creating a Directory
- Creating a Temporary Directory
- Listing a Directory’s Contents
- Filtering a Directory Listing By Using Globbing
- Writing Your Own Directory Filter
How to Create a Folder 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 :
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.1 Create a single directory.
1.2 Create a directory named “Directory2 and all its sub-directories “Sub2” and “Sub-Sub2” together.
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.
File file = new File("Library\\test.txt");
file.mkdir();
file.createNewFile();
File file = new File("Library\\test.txt");
file.getParentFile().mkdir();
file.createNewFile();
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.
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
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.
Creating new folder in java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Creating and Reading Directories
Some of the methods previously discussed, such as delete , work on files, links and directories. But how do you list all the directories at the top of a file system? How do you list the contents of a directory or create a directory?
This section covers the following functionality specific to directories:
Listing a File System’s Root Directories
You can list all the root directories for a file system by using the FileSystem.getRootDirectories method. This method returns an Iterable , which enables you to use the enhanced for statement to iterate over all the root directories.
The following code snippet prints the root directories for the default file system:
Iterable dirs = FileSystems.getDefault().getRootDirectories(); for (Path name: dirs)
Creating a Directory
You can create a new directory by using the createDirectory(Path, FileAttribute) method. If you don’t specify any FileAttributes , the new directory will have default attributes. For example:
Path dir = . ; Files.createDirectory(path);
The following code snippet creates a new directory on a POSIX file system that has specific permissions:
Set perms = PosixFilePermissions.fromString("rwxr-x---"); FileAttributeattr = PosixFilePermissions.asFileAttribute(perms); Files.createDirectory(file, attr);
To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method, createDirectories(Path, FileAttribute) . As with the createDirectory(Path, FileAttribute) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:
Files.createDirectories(Paths.get("foo/bar/test"));
The directories are created, as needed, from the top down. In the foo/bar/test example, if the foo directory does not exist, it is created. Next, the bar directory is created, if needed, and, finally, the test directory is created.
It is possible for this method to fail after creating some, but not all, of the parent directories.
Creating a Temporary Directory
You can create a temporary directory using one of createTempDirectory methods:
The first method allows the code to specify a location for the temporary directory and the second method creates a new directory in the default temporary-file directory.
Listing a Directory’s Contents
You can list all the contents of a directory by using the newDirectoryStream(Path) method. This method returns an object that implements the DirectoryStream interface. The class that implements the DirectoryStream interface also implements Iterable , so you can iterate through the directory stream, reading all of the objects. This approach scales well to very large directories.
Remember: The returned DirectoryStream is a stream. If you are not using a try- with-resources statement, don’t forget to close the stream in the finally block. The try- with-resources statement takes care of this for you.
The following code snippet shows how to print the contents of a directory:
Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir)) < for (Path file: stream) < System.out.println(file.getFileName()); >> catch (IOException | DirectoryIteratorException x) < // IOException can never be thrown by the iteration. // In this snippet, it can only be thrown by newDirectoryStream. System.err.println(x); >
The Path objects returned by the iterator are the names of the entries resolved against the directory. So, if you are listing the contents of the /tmp directory, the entries are returned with the form /tmp/a , /tmp/b , and so on.
This method returns the entire contents of a directory: files, links, subdirectories, and hidden files. If you want to be more selective about the contents that are retrieved, you can use one of the other newDirectoryStream methods, as described later in this page.
Note that if there is an exception during directory iteration then DirectoryIteratorException is thrown with the IOException as the cause. Iterator methods cannot throw exception exceptions.
Filtering a Directory Listing By Using Globbing
If you want to fetch only files and subdirectories where each name matches a particular pattern, you can do so by using the newDirectoryStream(Path, String) method, which provides a built-in glob filter. If you are not familiar with glob syntax, see What Is a Glob?
For example, the following code snippet lists files relating to Java: .class, .java, and .jar files.:
Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.")) < for (Path entry: stream) < System.out.println(entry.getFileName()); >> catch (IOException x) < // IOException can never be thrown by the iteration. // In this snippet, it can // only be thrown by newDirectoryStream. System.err.println(x); >
Writing Your Own Directory Filter
Perhaps you want to filter the contents of a directory based on some condition other than pattern matching. You can create your own filter by implementing the DirectoryStream.Filter interface. This interface consists of one method, accept , which determines whether a file fulfills the search requirement.
For example, the following code snippet implements a filter that retrieves only directories:
DirectoryStream.Filter filter = newDirectoryStream.Filter() < public boolean accept(Path file) throws IOException < try < return (Files.isDirectory(path)); >catch (IOException x) < // Failed to determine if it's a directory. System.err.println(x); return false; >> >;
Once the filter has been created, it can be invoked by using the newDirectoryStream(Path, DirectoryStream.Filter) method. The following code snippet uses the isDirectory filter to print only the directory’s subdirectories to standard output:
Path dir = . ; try (DirectoryStream stream = Files.newDirectoryStream(dir, filter)) < for (Path entry: stream) < System.out.println(entry.getFileName()); >> catch (IOException x)
This method is used to filter a single directory only. However, if you want to find all the subdirectories in a file tree, you would use the mechanism for Walking the File Tree.