- How to Create a New Folder in Java
- How to create a folder in Java?
- How to Create a New Folder in Java
- Creating Hierarchy of new Folders
- How to create a directory in Java?
- How to make a folder hidden using java
- How to create 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 New Folder in Java
The mkdirs() method creates a hierarchy of new folders or directories. The File class of Java provide a way through which we can make or create a directory or folder.
How to create a folder in Java?
How can I create an empty 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)
Call File.mkdir , like this:
With Java 7 and newer you can use the static Files.createDirectory() method of the java.nio.file.Files class along with Paths.get .
Files.createDirectory(Paths.get("/path/to/folder"));
The method Files.createDirectories() also creates parent directories if these do not exist.
new File('/path/to/folder').mkdir();
How to End a Java Program, Conclusion. To end or terminate a program in Java, use the System.exit () method or a return statement. Both ways are helpful, but the most commonly used approach is the System.exit () method. The System.exit () method terminates the currently executing JVM, whereas the return statement is used to …
How to Create a New Folder in Java
In Java, we can use the File object to Create a New Folder or directory. The File class of Java provide a way through which we can make or create a directory or folder. We use the mkdir() method of the File class to Create a new folder.
For creating a directory, we first have to create an instance of the File class and pass a parameter to that instance. This parameter is the path of the directory where we need to create it. After that, we have to invoke the mkdir() method using that file object.
Let’s use the mkdir() method to create a directory or folder through a Java program.
CreateFolder.java
//Import file class import java.io.File; //Import Scanner class import java.util.Scanner; public class CreateFolder < //Main() method start public static void main(String args[]) < //Using Scanner class to get the path from the user where he wants to create a folder. System.out.println("Enter the path where you want to create a folder: "); Scanner sc = new Scanner(System.in); String path = sc.next(); //Using Scanner class to get the folder name from the user System.out.println("Enter the name of the desired a directory: "); path = path+sc.next(); //Instantiate the File class File f1 = new File(path); //Creating a folder using mkdir() method boolean bool = f1.mkdir(); if(bool)< System.out.println("Folder is created successfully"); >else < System.out.println("Error Found!"); >> >
If we go to that location, we will see the created folder as:
Note: If we enter an unavailable path, the mkdir() method will not create a folder and pass the control flow to the else part.
Creating Hierarchy of new Folders
The drawback of the mkdir() method is resolved by the mkdirs() method. The mkdirs() method is more powerful than mkdir() method. The mkdirs() method creates a hierarchy of new folders or directories. It creates a folder in the same way as the mkdir() method, but it also creates the parent folders too that do not exist.
Let’s take an example to understand how the mkdirs() method is different from the mkdir() method.
CreateFolderHierarchy.java
import java.io.File; import java.util.Scanner; public class CreateFolderHierarchy < //main() method start public static void main(String args[]) < //Using Scanner class to get the path from the user where he wants to create a folder. System.out.println("Enter the path where you want to create a folder: "); Scanner sc = new Scanner(System.in); String path = sc.next(); //Using Scanner class to get the folder name from the user System.out.println("Enter the name of the desired a directory: "); path = path+sc.next(); //Instantiate the File class File f1 = new File(path); //Creating a folder using mkdirs() method boolean bool2 = f1.mkdirs(); if(bool2)< System.out.println("Folder is created successfully"); >else < System.out.println("Error Found!"); >> >
When we access the desired location, we see the created folder. If the user enters an unavailable location, the mkdirs() make it available by creating all the parent folders that do not exist in the system.
Java Create and Write To Files, To create a file in Java, you can use the createNewFile () method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a trycatch block.
How to create a directory in Java?
Once I have tested System.getProperty(«user.home»);
I have to create a directory (directory name «new folder» ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here «directory» is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by bozho.
File theDir = new File("/path/directory"); if (!theDir.exists())
With Java 7, you can use Files.createDirectories() .
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
Java File Upload to a Folder, In this section, we will learn about how we can implement the file upload functionality in Java and will also understand how to upload a file to a folder. In Java, we use a single servlet and an HTML form for creating a file upload request to the servlet. We implement a Simple HTML form having two fields, i.e., File and …
How to make a folder hidden using java
I want to create a hidden folder using java application. That program should work across platform. So How to write a program which can create hidden folder.
File newFile = new File("myfile"); newFile.mkdir();
It creates a directory which is not hidden.
If you’re using Java 7 you can use the new java.nio.file.attribute package like so:
Path path = FileSystems.getDefault().getPath("/j", "sa"); Files.setAttribute(path, "dos:hidden", true);
See more info at http://download.oracle.com/javase/tutorial/essential/io/fileAttr.html
Or, if you’re using an older version of Java and/or want to do it using Runtime , try this:
Process process = Runtime.getRuntime().exec("cmd.exe /C attrib -s -h -r your_path");
See more info on cmd and attrib.
The concept of hidden files/folders is very OS-specific and not accessible via the Java API.
In Linux, files and folders whose name begins with a dot are hidden per default in many programs — doing that is easy.
In Windows, «hidden» is a special flag stored in the file system. There is no Java API for changing it; you can use Runtime.exec() to run the attrib command.
under *nix you just rename the file so that
To make a file or directory hidden under Unix, its name needs to start with a period ( . ).
To make a file hidden under Windows, you need to set the ‘hidden’ bit in its attributes. The Java standard library doesn’t offer this capability (though there is a file.isHidden() method), and I don’t offhand know any tool that does.
How to Convert double to int in Java, Method 2: Convert double to int in Java by Using Double.intValue () Method. Double.intValue () is another method used to convert the number from double data type to int. The “ intValue () ” is the method of the Java “ Double ” Wrapper class. This method converts the double value into the nearest integer …
How to create 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.