Создать каталог в Java
В этом посте будет обсуждаться, как создать каталог в Java, включая все несуществующие родительские каталоги.
1. Использование File#mkdirs() метод
Стандартным решением для создания каталога является использование mkdir() метод из File учебный класс. Возвращает true, если каталог создан; ложно в противном случае. Вызов этого метода будет выглядеть следующим образом:
Обратите внимание, что mkdir() метод полезен для создания одного каталога. Если вы хотите создать иерархию папок, вы должны использовать mkdirs() метод вместо этого. Он создает каталог, названный абстрактным путем, включая любые несуществующие родительские каталоги.
Например, следующий код создает родительский каталог с именем path (если не существует), за которым следует его подкаталог dir .
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:
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:
The following code snippet creates a new directory on a POSIX file system that has specific permissions:
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:
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:
- createTempDirectory(Path, String, FileAttribute<?>. )
- createTempDirectory(String, FileAttribute<?>. )
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.
The following code snippet shows how to print the contents of a directory:
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.:
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<T> 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:
Once the filter has been created, it can be invoked by using the newDirectoryStream(Path, DirectoryStream.Filter<? super Path>) method. The following code snippet uses the isDirectory filter to print only the directory's subdirectories to standard output:
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.
How to create a directory in Java?
I have to create a directory (directory name «new folder» ) if and only if new folder does not exist.
16 Answers 16
Here «directory» is the name of the directory you want to create/exist.
![]()
7 year, I will update it to better approach which is suggested by Bozho.
![]()
![]()
This library have a lot of useful functions.
![]()
mkdir vs mkdirs
If you want to create a single directory use mkdir
If you want to create a hierarchy of folder structure use mkdirs
![]()
Create a single directory.
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
Source: this perfect tutorial , you find also an example of use.
![]()
![]()
For java 7 and up:
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
Name already in use
java_notes / IO / java.io.File.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Класс предназначен для манипуляции файлами и каталогами, чтения и установки атрибутов. Файлы можно создавать, удалять, переименовывать и т.п..
Методы анализа файла
| Метод | Описание |
|---|---|
| boolean isDirectory() | Является ли «объект файла» директорией |
| boolean isFile() | Является ли объект файлом |
| Ьoolean isHidden() | Является ли файл скрытым |
| long length() | Возвращает размер/длину файла в байтах. |
| boolean exists() | Возвращает true, если файл с таким именем существует на диске компьютера. |
| String getAbsolutePath() | Возвращает полный путь файла со всеми поддиректориями. |
| String getCanonicalPath() | Возвращает канонический путь файла. Например, преобразовывает путь «c:/dir/dir2/../a.txt» к пути «c:/dir/a.txt» |
| String getName() | Возвращает только имя файла, без пути. |
| String getParent() | Возвращает только путь (директорию) к текущему файлу, без самого имени. |
| File getParentFile() | Возвращает только путь (директорию) к текущему файлу как объект File |
| Метод | Описание |
|---|---|
| boolean createNewFile() | Создает файл. Если такой файл уже был, возвращает false. |
| boolean delete() | Удаляет файл объекта на диске. Если объект – директория, то только, если в ней нет файлов. |
| void deleteOnExit() | Добавляет файл в специальный список файлов, которые будут автоматически удалены при закрытии программы. |
| File createTempFile(String prefix, String suffix, File directory) | Создает «временный файл» — файл с случайно сгенерированным уникальным именем – что-типа «dasd4d53sd». Дополнительные параметры – префикс к имени, суффикс (окончание). Если директория не указана, то файл создается в специальной директории ОС для временных файлов |
| boolean renameTo(File) | Переименовывает файл – содержимое файла фактически получает новое имя. Т.е. можно переименовать файл «c:/dir/a.txt» в «d:/out/text/b.doc». |
| Метод | Описание |
|---|---|
| boolean mkdir() | Создает директорию. Название mkdir происходит от «make directory». |
| boolean mkdirs() | Создает директорию и все поддиректории. |
| String[] list() | Возвращает массив имен файлов, которые содержатся в директории, которой является текущий объект-файл. |
| String[] list(FilenameFilter filter) | возвращает файлы ограниченные filter — функциональный интерфейс boolean accept (File dir, String name) |
| File[] listFiles() | Возвращает массив файлов, которые содержатся в директории, которой является текущий объект-файл. |
| File[] listFiles(FileFilter filter) | FileFilter — функ.интерфейс boolean accept(File pathname) |
| File[] listFiles(FilenameFilter filter) | Возвращает массив файлов, которые содержатся в директории, которой является текущий объект-файл, ограниченные filter |
Вывести на экран список всех файлов, которые находятся в определенной директории
Вывести имена всех файлов, которые есть в той же директории, что и текущий файл