Создать папку java file

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---"); 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 file

Класс File, определенный в пакете java.io, не работает напрямую с потоками. Его задачей является управление информацией о файлах и каталогах. Хотя на уровне операционной системы файлы и каталоги отличаются, но в Java они описываются одним классом File.

В зависимости от того, что должен представлять объект File — файл или каталог, мы можем использовать один из конструкторов для создания объекта:

File(String путь_к_каталогу) File(String путь_к_каталогу, String имя_файла) File(File каталог, String имя_файла)
// создаем объект File для каталога File dir1 = new File("C://SomeDir"); // создаем объекты для файлов, которые находятся в каталоге File file1 = new File("C://SomeDir", "Hello.txt"); File file2 = new File(dir1, "Hello2.txt");

Класс File имеет ряд методов, которые позволяют управлять файлами и каталогами. Рассмотрим некоторые из них:

  • boolean createNewFile() : создает новый файл по пути, который передан в конструктор. В случае удачного создания возвращает true, иначе false
  • boolean delete() : удаляет каталог или файл по пути, который передан в конструктор. При удачном удалении возвращает true.
  • boolean exists() : проверяет, существует ли по указанному в конструкторе пути файл или каталог. И если файл или каталог существует, то возвращает true, иначе возвращает false
  • String getAbsolutePath() : возвращает абсолютный путь для пути, переданного в конструктор объекта
  • String getName() : возвращает краткое имя файла или каталога
  • String getParent() : возвращает имя родительского каталога
  • boolean isDirectory() : возвращает значение true, если по указанному пути располагается каталог
  • boolean isFile() : возвращает значение true, если по указанному пути находится файл
  • boolean isHidden() : возвращает значение true, если каталог или файл являются скрытыми
  • long length() : возвращает размер файла в байтах
  • long lastModified() : возвращает время последнего изменения файла или каталога. Значение представляет количество миллисекунд, прошедших с начала эпохи Unix
  • String[] list() : возвращает массив файлов и подкаталогов, которые находятся в определенном каталоге
  • File[] listFiles() : возвращает массив файлов и подкаталогов, которые находятся в определенном каталоге
  • boolean mkdir() : создает новый каталог и при удачном создании возвращает значение true
  • boolean renameTo(File dest) : переименовывает файл или каталог

Работа с каталогами

Если объект File представляет каталог, то его метод isDirectory() возвращает true . И поэтому мы можем получить его содержимое — вложенные подкаталоги и файлы с помощью методов list() и listFiles() . Получим все подкаталоги и файлы в определенном каталоге:

import java.io.File; public class Program < public static void main(String[] args) < // определяем объект для каталога File dir = new File("C://SomeDir"); // если объект представляет каталог if(dir.isDirectory()) < // получаем все вложенные объекты в каталоге for(File item : dir.listFiles())< if(item.isDirectory())< System.out.println(item.getName() + " \t folder"); >else < System.out.println(item.getName() + "\t file"); >> > > >

Теперь выполним еще ряд операций с каталогами, как удаление, переименование и создание:

import java.io.File; public class Program < public static void main(String[] args) < // определяем объект для каталога File dir = new File("C://SomeDir//NewDir"); boolean created = dir.mkdir(); if(created) System.out.println("Folder has been created"); // переименуем каталог File newDir = new File("C://SomeDir//NewDirRenamed"); dir.renameTo(newDir); // удалим каталог boolean deleted = newDir.delete(); if(deleted) System.out.println("Folder has been deleted"); >>

Работа с файлами

Работа с файлами аналогична работе с каталога. Например, получим данные по одному из файлов и создадим еще один файл:

import java.io.File; import java.io.IOException; public class Program < public static void main(String[] args) < // определяем объект для каталога File myFile = new File("C://SomeDir//notes.txt"); System.out.println("File name: " + myFile.getName()); System.out.println("Parent folder: " + myFile.getParent()); if(myFile.exists()) System.out.println("File exists"); else System.out.println("File not found"); System.out.println("File size: " + myFile.length()); if(myFile.canRead()) System.out.println("File can be read"); else System.out.println("File can not be read"); if(myFile.canWrite()) System.out.println("File can be written"); else System.out.println("File can not be written"); // создадим новый файл File newFile = new File("C://SomeDir//MyFile"); try < boolean created = newFile.createNewFile(); if(created) System.out.println("File has been created"); >catch(IOException ex) < System.out.println(ex.getMessage()); >> >

При создании нового файла метод createNewFile() в случае неудачи выбрасывает исключение IOException , поэтому нам надо его отлавливать, например, в блоке try. catch, как делается в примере выше.

Источник

Создание каталога в Java

В Java существует несколько способов создания каталогов: с помощью методов File.mkdir() и File.mkdirs() .

1. Для создания одного каталога предназначен метод mkdir() :

2. Для создания каталога, а также всех родительских каталогов, предназначен метод mkdirs() :

new File("C:\Directory\SubDirectory1\SubDirectory2").mkdirs();

Оба эти метода возвращают булево значение: true если каталог (во втором случае — со всеми родительскими каталогами) создан успешно и false при возникновении проблем.

Пример

Классический пример создания каталогов в Java: проверить, существует ли каталог и если нет — создать его.

package ru.j4web.examples.java.io; import java.io.File; public class CreateDirectoryExample < private static final String DIR1 = "c:\Projects\J4Web.Ru\Src\" + "JavaIO\CreateDirectoryExample\Dir1"; private static final String DIR2 = "c:\Projects\J4Web.Ru\Src\" + "JavaIO\CreateDirectoryExample\Dir2\Dir3\Dir4\Dir5"; public static void main(String[] args) < final File dir1 = new File(DIR1); if(!dir1.exists()) < if(dir1.mkdir()) < System.out.println("Каталог " + dir1.getAbsolutePath() + " успешно создан."); >else < System.out.println("Каталог " + dir1.getAbsolutePath() + " создвть не удалось."); >> else < System.out.println("Каталог " + dir1.getAbsolutePath() + " уже существует."); >final File dir2 = new File(DIR2); if(!dir2.exists()) < if(dir2.mkdirs()) < System.out.println("Каталог " + dir2.getAbsolutePath() + " успешно создан."); >else < System.out.println("Каталог " + dir2.getAbsolutePath() + " создвть не удалось."); >> else < System.out.println("Каталог " + dir2.getAbsolutePath() + " уже существует."); >> >

Полезная информация

Источник

Читайте также:  Цвет фона всего php
Оцените статью