path что это java
Path что это java
This interface extends Watchable interface so that a directory located by a path can be registered with a WatchService and entries in the directory watched.
WARNING: This interface is only intended to be implemented by those developing custom file system implementations. Methods may be added to this interface in future releases.
Accessing Files
Paths may be used with the Files class to operate on files, directories, and other types of files. For example, suppose we want a BufferedReader to read text from a file » access.log «. The file is located in a directory » logs » relative to the current working directory and is UTF-8 encoded.
Interoperability
Concurrency
Implementations of this interface are immutable and safe for use by multiple concurrent threads.
Method Summary
Modifier and Type | Method and Description |
---|---|
int | compareTo(Path other) |
Method Detail
getFileSystem
isAbsolute
An absolute path is complete in that it doesn’t need to be combined with other path information in order to locate a file.
getRoot
getFileName
getParent
The parent of this path object consists of this path’s root component, if any, and each element in the path except for the farthest from the root in the directory hierarchy. This method does not access the file system; the path or its parent may not exist. Furthermore, this method does not eliminate special names such as «.» and «..» that may be used in some implementations. On UNIX for example, the parent of » /a/b/c » is » /a/b «, and the parent of «x/y/. » is » x/y «. This method may be used with the normalize method, to eliminate redundant names, for cases where shell-like navigation is required.
If this path has one or more elements, and no root component, then this method is equivalent to evaluating the expression:
getNameCount
getName
subpath
startsWith
This path starts with the given path if this path’s root component starts with the root component of the given path, and this path starts with the same name elements as the given path. If the given path has more name elements than this path then false is returned.
Whether or not the root component of this path starts with the root component of the given path is file system specific. If this path does not have a root component and the given path has a root component then this path does not start with the given path.
If the given path is associated with a different FileSystem to this path then false is returned.
startsWith
endsWith
If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.
If the given path has a root component then this path ends with the given path if the root component of this path ends with the root component of the given path, and the corresponding elements of both paths are equal. Whether or not the root component of this path ends with the root component of the given path is file system specific. If this path does not have a root component and the given path has a root component then this path does not end with the given path.
If the given path is associated with a different FileSystem to this path then false is returned.
endsWith
normalize
resolve
resolve
resolveSibling
resolveSibling
relativize
For any two normalized paths p and q, where q does not have a root component,
toUri
This method constructs an absolute URI with a scheme equal to the URI scheme that identifies the provider. The exact form of the scheme specific part is highly provider dependent.
The default provider provides a similar round-trip guarantee to the File class. For a given Path p it is guaranteed that
When a file system is constructed to access the contents of a file as a file system then it is highly implementation specific if the returned URI represents the given path in the file system or it represents a compound URI that encodes the URI of the enclosing file system. A format for compound URIs is not defined in this release; such a scheme may be added in a future release.
toAbsolutePath
If this path is already absolute then this method simply returns this path. Otherwise, this method resolves the path in an implementation dependent manner, typically by resolving the path against a file system default directory. Depending on the implementation, this method may throw an I/O error if the file system is not accessible.
toRealPath
The precise definition of this method is implementation dependent but in general it derives from this path, an absolute path that locates the same file as this path, but with name elements that represent the actual name of the directories and the file. For example, where filename comparisons on a file system are case insensitive then the name elements represent the names in their actual case. Additionally, the resulting path has redundant name elements removed.
If this path is relative then its absolute path is first obtained, as if by invoking the toAbsolutePath method.
toFile
register
The context for these events is the relative path between the directory located by this path, and the path that locates the directory entry that is created, deleted, or modified.
The set of events may include additional implementation specific event that are not defined by the enum StandardWatchEventKinds
The modifiers parameter specifies modifiers that qualify how the directory is registered. This release does not define any standard modifiers. It may contain implementation specific modifiers.
Where a file is registered with a watch service by means of a symbolic link then it is implementation specific if the watch continues to depend on the existence of the symbolic link after it is registered.
register
An invocation of this method behaves in exactly the same way as the invocation
Usage Example: Suppose we wish to register a directory for entry create, delete, and modify events:
iterator
The first element returned by the iterator represents the name element that is closest to the root in the directory hierarchy, the second element is the next closest, and so on. The last element returned is the name of the file or directory denoted by this path. The root component, if present, is not returned by the iterator.
compareTo
This method may not be used to compare paths that are associated with different file system providers.
equals
Whether or not two path are equal depends on the file system implementation. In some cases the paths are compared without regard to case, and others are case sensitive. This method does not access the file system and the file is not required to exist. Where required, the isSameFile method may be used to check if two paths locate the same file.
This method satisfies the general contract of the Object.equals method.
hashCode
The hash code is based upon the components of the path, and satisfies the general contract of the Object.hashCode method.
toString
If this path was created by converting a path string using the getPath method then the path string returned by this method may differ from the original String used to create the path.
The returned path string uses the default name separator to separate names in the path.
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
NIO (Java, обучающая статья)
Предисловие
За основу данной статьи была взята информация из 9-ой главы книги «Oracle Certified Professional Java SE 7 Programmers Exams 1Z0-804 and 1Z0-805». Она была немного изменена (кое-где обрезана, а кое-где дополнена с помощью Google и Википедии). Здесь показаны далеко не все возможности NIO — для более подробной информации следует обратиться к официальной документации. Приятного прочтения.
Немного терминологии
Интерфейс программирования приложений (иногда интерфейс прикладного программирования) (англ. application programming interface, API) — набор готовых классов, процедур, функций, структур и констант, предоставляемых приложением (библиотекой, сервисом) для использования во внешних программных продуктах.
I/O (input/output, Ввод-вывод ) — взаимодействие между обработчиком информации и её поставщиком и/или получателем. Ввод — сигнал или данные, полученные обработчиком, а вывод — сигнал или данные, посланные им (или из него).
NIO ( /*в контексте Java*/ Non-blocking I/O, New I/O) — коллекция прикладных программных интерфейсов для языка Java, предназначенных для реализации высокопроизводительных операций ввода-вывода. Также встречается аббревиатура NIO.2 – она относится к нововведениям относительно этого направления в Java 7.
Символьная ссылка (Symbolic link, симлинк) — специальный файл в файловой системе, содержащий только текстовую строку с указателем. Эта строка трактуется как путь к файлу, который должен быть открыт при попытке обратиться к данному файлу.
Абсолютный путь — это путь, который указывает на одно и то же место в файловой системе, вне зависимости от текущей директории. Полный путь всегда начинается с корневого каталога.
Относительный путь — это путь по отношению к текущему рабочему каталогу.
Немного истории
Изначально Java предоставляла класс File (в пакете java.io) для доступа к файловым системам. Этот класс представляет файл/каталог в файловой системе и позволяет выполнять такие операции, как проверка на существование файла/каталога, получении свойств, и удаление файла/каталога. Тем не менее, первый вариант API не был достаточен для удовлетворения потребностей разработчиков. Ощущалась явная необходимость доработки I/O API.
Краткий список недостатков первой I/O API:
Для преодоления этих проблем, в Java 4 введен NIO (New IO). Ключевые особенности NIO:
В Java 7 был введён пакет java.nio.file для лучшей поддержки и обработки символьных ссылок, полного доступа к атрибутам и работы с файловой системой через интерфейсы или классы, такие как Path, Paths, and Files.
Использование интерфейса Path
Java 7 представляет новую абстракцию для пути, а именно интерфейс Path. Он используется в новых функциях и API, по всему NIO.2. Объект пути содержит имена каталогов и файлов, которые составляют полный путь до файла/каталога, представленного объектом Path; Path содержит методы для извлечения элементов пути, манипуляций с ними и их добавления.
Ниже приведён пример кода, для выполнения на Unux-системе, но пользователи Windows могут раскомментировать одну строку и закомментировать другую, для выполнения примера на своих машиах (см. комментарии в коде). Существование соответствующих файлов и катологов (test и testfile.txt) в файловой системе не обязательно. В этом примере создаётся объект Path и извлекается основная информация, связанная с ним:
Вывод получается такой:
Перейдём к другому примеру который включает получение абсолютного пути от относительного пути и нормализацию пути:
Пример вывода при выполнении данного кода (файл Test не должен существовать в файловой системе для аналогичного вывода):
(Пользователи Windows-систем получат sun.nio.fs.WindowsException.translateToIOException вместо sun.nio.fs.UnixException.translateToIOException и т. д. и т.п.)
Пример вывода при выполнении данного кода (файл Test должен существовать в файловой системе для аналогичного вывода):
Интерфейс Path содержит два метода для сравнения объектов Path: equals() and compareTo(). Метод equals() сравнивает пути и возвращает Boolean. Метод compareTo() сравнивает пути посимвольно и возвращает: 0, если пути равны; отрицательное целое значение, если путь в объекте вызывающем метод лексикографически меньше пути в объекте, переданном в качестве параметра; положительное целое значение в противоположном случае.
Последний System.out.println является подсказкой — он выводит путь, который должен быть передан в path2 для аналогичного вывода. Вывод должен получится такой:
Использование класса Files
Рассмотрим класс Files (введён в Java 7, находится в пакете java.nio.file), который можно использовать для выполнения различных операций с файлами и каталогами. Files является служебным классом, это означает, что это final-класс с private-конструктором и содержит только статические методы. В этом классе находится множество методов для выполнения различных действий. Рассмотрим некоторые из них.
Выше был показан пример кода, в котором выяснялось, указывают ли два пути на один файл. Сущесвует способ проверить это с помощью метода isSameFile () из класса Files:
Т.к. тут сравниваются файлы, а не пути, то существование соответствующего файла обязательно (см. подсказку для пути в предыдущем примере) иначе будет получена ошибка java.nio.file.NoSuchFileException.
В случае, если файл по указанному адресу существует, получим такой вывод:
Можно определить, имеем мы дело с файлом или директорией (папкой) с помощью метода isDirectory() класса Files и проверить их существование с помощью метода exists():
Вывод должен получится примерно такой (выбирайте пути в соответствии с вашей ОС и расположением файлов):
Интересный вывод можно получить, если написать Path path = Paths.get(«/»); для Unix-систем или Path path = Paths.get(«С:\\»); для Windows-систем, т.е. если передать в качестве параметра имя корневого котолога:
Для корневого каталога path.getFileName() возвращает null.
Класс Files содержит методы isReadable(), isWriteable() и isExecutable() для проверки возможности чтения, записи и выполнения файлов:
Метод getAttribute() позволяет получить свойства (атрибуты) файла. Метод принимает переменное число параметров: первый — объект Path; второй — имя атрибута; далее от нуля до нескольких значений LinkOption (это enum):
Коппирование файлов
Теперь рассмотрим коппирование файла/диретории. Для этого используем метод Files.copy(). Сигнатура данного метода:
Первый параметр — путь к исходному файлу, второй — путь к тому файлу, что будет создан в результате копирования (включая имя нового файла), далее можно задать параметры копирования,а можно и не задать, как в примере ниже:
После первого запуска всё должно отработать корректно для корректных путей. Но если данный код без изменений скомпилировать и выполнить повторно, то будет получено исключение java.nio.file.FileAlreadyExistsException. Оно связано с тем, что целевой файл уже существует. Для избежания таких проблем можно указать, чтобы в случае его существования он перезаписывался. Для этого надо немного изменить одну строку кода:
Следует отметить, что при копировании директории не будут копироваться содержащиеся в ней файлы и директории. Это выглядит глупо — ниже будет показано, как это исправить.
Перемещение файла
Метод для перемещения файла очень похож на метод для копирования:
Значения передаваемых параметров совпадают по смыслу. Пример кода отличается от предыдущего минимально:
Если при копировании директории содержащиеся в ней файлы и директории не копировались, то при её перемещении, в случае отсутствия ошибок, перемещается и всё содержимое.
Удаление файла
Посмотрим на пример кода:
Несколько моментов, которые необходимо помнить относительно метода Files.delete():
Обход дерева файлов
При работе с файловой системой может возникнуть необходимость обхода дерева файлов, например при поиске файла или копировании каталога со всем его содержимым. Класс Files содержит два метода, позволяющих обходить дерево файлов. Их сигнатуры приведены ниже:
Оба метода принимают путь, с которого начнётся обход дерева и экземпляр типа FileVisitor, который будет определять поведение при обходе дерева. Второй метод имеет два дополнительных параметра: Set, содержащий опции обхода, и максимальную глубину. Максимальная глубина определяет, насколько уровней каталогов будет происходить обход. Если в её качестве указать 0, то будет рассматриваться только указанный файл, а если указать MAX_VALUE, то будут пройдены все подкаталоги.
FileVisitor — это интерфейс, содержащий следующие методы:
Вам необходимо реализовать интерфейс FileVisitor, чтобы передать соответствующий объект в метод walkFileTree(). Но если необходимости реализовывать все четыре метода этого интерфейса нет, то можно просто расширить реализацию класса SimpleFileVisitor, переопределив лишь необходимые методы.
При выполнении данного кода будут выведены все вложенные каталоги и файлы по указанному пути. Вот что следует понять:
Доработка копирования файлов
Возвращаясь к «глупому» копированию каталога в котором что-то есть — используя полученные знания можно реализовать его более логично, относительно результата, ожидаемого пользователем:
В методе preVisitDirectory() происходит копирование посещаемого каталога и аналогично копируется файл в методе visitFile(). Чтобы получить новый путь назначения, используется метод relativize() из класса Path.
Поиск файлов
Поняв принципы обхода дерева файлов, можно легко организовать поиск нужного файла. При поиске конкретного файла/каталога можно проверять соответствие имени файла/каталога с искомым с помощью метода visitFile () или preVisitDirectory (). Однако, если необходимо найти все файлы, соответствующие некоторому шаблону (например, все исходные файлы Java или XML-файлы ), то лучше использовать использовать универсальный символ (glob) или регулярное выражение (regex). Тут пригодится интерфейс PathMatcher. Данный интерфейс реализован для каждой файловой системы и вы можете получить экземпляр этого типа из класса FileSystem используя метод getPathMatcher().
Перед тем, как перейти к примеру стоит пояснить шаблоны Glob (похожи на regex, но немного проще. Если понятие regex для Вас ново, то ближе с ним можно ознакомится здесь — Регулярные выражения в Java). В таблице ниже приведены шаблоны, поддерживаемые glob-синтаксисом:
Шаблон | Описание |
* | Соответствует любой строке любой длины, даже пустой. |
** | Как и *, но выходит за границы каталогов. |
? | Любой одиночный символ. |
[XYZ] | Либо X, либо Y, либо Z. |
5 | Соответствует любому символу от 0 до 5. |
[a–z] | Любой строчный символ латинского алфавита. |
Либо XYZ или ABC. |
Ниже приведён пример кода, который находит все java-файлы в указанном каталоге. Для поиска используется glob-шаблон, но в коментариях приведён regex-шаблон, который можно использовать для этой же цели. Обратите внимание, что в строке с шаблоном сначала указывается его тип (glob или regex), потом ставится доеточие, а потом пишется сам шаблон. Ради интереса можете запустить этот же код убрав первую часть с двоеточием, но сначала просто попробуйте скомпилировать и выполнить:
Отслеживание изменений в каталоге
Предположим, что необходимо написать некое приложение, работающее с файлами (IDE, файловый менеджер или какой-либо редактор). Допустим какой-либо файл, важный для приложения был либо создан, либо изменён, либо удалён из вне и надо сообщить об этом пользователю.
Java 7 предоставляет сервис для слежения за каталогами. Вы можете зарегистрировать в нём каталог, чтобы получать уведомления о любом изменении в каталоге (создание, изменение и удаление файла).
Рассмотрим API этого сервиса на примере. Для этого примера используйте каталог в котором при выполнении программы в бесконечном цикле Вы будете создавать, изменять и удалять файлы — действия должны выводится на консоли. Код ниже:
Основное различие между poll() и take() в том, что poll() это неблокирующий вызов, а take() — блокирующий.
Когда ключ возвращается, то одно или более событий могут быть помещены в очередь, именно поэтому используется ещё один цикл (для перебора всех событий).
Если Вам понравилась статья, проголосуйте за нее
Голосов: 48 Голосовать
Path что это java
This interface extends Watchable interface so that a directory located by a path can be registered with a WatchService and entries in the directory watched.
WARNING: This interface is only intended to be implemented by those developing custom file system implementations. Methods may be added to this interface in future releases.
Accessing Files
Paths may be used with the Files class to operate on files, directories, and other types of files. For example, suppose we want a BufferedReader to read text from a file » access.log «. The file is located in a directory » logs » relative to the current working directory and is UTF-8 encoded.
Interoperability
Concurrency
Implementations of this interface are immutable and safe for use by multiple concurrent threads.
Method Summary
Methods inherited from interface java.lang.Iterable
Method Detail
getFileSystem
isAbsolute
An absolute path is complete in that it doesn’t need to be combined with other path information in order to locate a file.
getRoot
getFileName
getParent
The parent of this path object consists of this path’s root component, if any, and each element in the path except for the farthest from the root in the directory hierarchy. This method does not access the file system; the path or its parent may not exist. Furthermore, this method does not eliminate special names such as «.» and «..» that may be used in some implementations. On UNIX for example, the parent of » /a/b/c » is » /a/b «, and the parent of «x/y/. » is » x/y «. This method may be used with the normalize method, to eliminate redundant names, for cases where shell-like navigation is required.
If this path has one or more elements, and no root component, then this method is equivalent to evaluating the expression:
getNameCount
getName
subpath
startsWith
This path starts with the given path if this path’s root component starts with the root component of the given path, and this path starts with the same name elements as the given path. If the given path has more name elements than this path then false is returned.
Whether or not the root component of this path starts with the root component of the given path is file system specific. If this path does not have a root component and the given path has a root component then this path does not start with the given path.
If the given path is associated with a different FileSystem to this path then false is returned.
startsWith
endsWith
If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.
If the given path has a root component then this path ends with the given path if the root component of this path ends with the root component of the given path, and the corresponding elements of both paths are equal. Whether or not the root component of this path ends with the root component of the given path is file system specific. If this path does not have a root component and the given path has a root component then this path does not end with the given path.
If the given path is associated with a different FileSystem to this path then false is returned.
endsWith
normalize
resolve
resolve
resolveSibling
resolveSibling
relativize
For any two normalized paths p and q, where q does not have a root component,
toUri
This method constructs an absolute URI with a scheme equal to the URI scheme that identifies the provider. The exact form of the scheme specific part is highly provider dependent.
The default provider provides a similar round-trip guarantee to the File class. For a given Path p it is guaranteed that
When a file system is constructed to access the contents of a file as a file system then it is highly implementation specific if the returned URI represents the given path in the file system or it represents a compound URI that encodes the URI of the enclosing file system. A format for compound URIs is not defined in this release; such a scheme may be added in a future release.
toAbsolutePath
If this path is already absolute then this method simply returns this path. Otherwise, this method resolves the path in an implementation dependent manner, typically by resolving the path against a file system default directory. Depending on the implementation, this method may throw an I/O error if the file system is not accessible.
toRealPath
The precise definition of this method is implementation dependent but in general it derives from this path, an absolute path that locates the same file as this path, but with name elements that represent the actual name of the directories and the file. For example, where filename comparisons on a file system are case insensitive then the name elements represent the names in their actual case. Additionally, the resulting path has redundant name elements removed.
If this path is relative then its absolute path is first obtained, as if by invoking the toAbsolutePath method.
toFile
register
The context for these events is the relative path between the directory located by this path, and the path that locates the directory entry that is created, deleted, or modified.
The set of events may include additional implementation specific event that are not defined by the enum StandardWatchEventKinds
The modifiers parameter specifies modifiers that qualify how the directory is registered. This release does not define any standard modifiers. It may contain implementation specific modifiers.
Where a file is registered with a watch service by means of a symbolic link then it is implementation specific if the watch continues to depend on the existence of the symbolic link after it is registered.
register
An invocation of this method behaves in exactly the same way as the invocation
Usage Example: Suppose we wish to register a directory for entry create, delete, and modify events:
iterator
The first element returned by the iterator represents the name element that is closest to the root in the directory hierarchy, the second element is the next closest, and so on. The last element returned is the name of the file or directory denoted by this path. The root component, if present, is not returned by the iterator.
compareTo
This method may not be used to compare paths that are associated with different file system providers.
equals
Whether or not two path are equal depends on the file system implementation. In some cases the paths are compared without regard to case, and others are case sensitive. This method does not access the file system and the file is not required to exist. Where required, the isSameFile method may be used to check if two paths locate the same file.
This method satisfies the general contract of the Object.equals method.
hashCode
The hash code is based upon the components of the path, and satisfies the general contract of the Object.hashCode method.
toString
If this path was created by converting a path string using the getPath method then the path string returned by this method may differ from the original String used to create the path.
The returned path string uses the default name separator to separate names in the path.
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2021, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.