Folder directory in java

How to create a directory in project folder using Java?

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.

The mkdir() method of this class creates a directory with the path represented by the current object.

Therefore, to create a directory −

  • Instantiate the File class by passing the path of the directory you need to create, as a parameter (String).
  • Invoke the mkdir() method using the above-created file object.

Example

The following Java example reads the path and name of the directory to be created, from the user, and creates it.

import java.io.File; import java.util.Scanner; public class CreateDirectory < public static void main(String args[]) < System.out.println("Enter the path to create a directory: "); Scanner sc = new Scanner(System.in); String path = sc.next(); System.out.println("Enter the name of the desired a directory: "); path = path+sc.next(); //Creating a File object File file = new File(path); //Creating the directory boolean bool = file.mkdir(); if(bool)< System.out.println("Directory created successfully"); >else < System.out.println("Sorry couldn’t create specified directory"); >> >

Output

Enter the path to create a directory: D:\ Enter the name of the desired a directory: sample_directory Directory created successfully

If you verify, you can observe see the created directory as −

But, if you specify a path in a drive that doesn’t exist, this method will not create the required directory.

For example, if the D drive of my (windows) system is empty and if I specify the path of the directory to be created as −

D:\test\myDirectories\sample_directory

Where the test and myDirectories folders don’t exist, the mkdir() method will not create it.

Источник

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?

Читайте также:  Что такое setdefault питон

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---"); FileAttribute attr = 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.

Источник

Java create directory example

Java create directory example shows how to create a directory in Java. The example also shows how to create directories including all parent directories or folders.

How to create a directory in Java?

Java File class provides two methods mkdir and mkdirs which can be used to create directories.

This method creates a directory denoted by the file object. It returns true if the directory was created successfully, false otherwise.

Java Create Directory Example

If you re-run the same program, the output will be “Failed to create directory” because the directory was already created in the first run.

How to create all required directories including non-existent parent directories?

Consider the following code.

If dir_1 does not exist, the above-given code will fail to create the dir_2. If you want to create all directories including non-existent parent directories, use the mkdirs method instead of the mkdir method.

Is it necessary to check if a directory exists before creating it?

You might think that it would be a good idea to check if the directory exists before actually creating it using the exists method like given below.

The above-given code calls the mkdir method only if the directory does not exist. Here a call to the exists method is not necessary because mkdir returns true if and only if the directory was created successfully. So even if the directory exists, the mkdir method will not cause any harm neither it will throw any exceptions.

How to create directories using Java 7 NIO?

If you are using JDK 7 or a later version, you can use Paths and Files classes to create directories as given below.

Источник

Folder directory in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

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 RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью