Проверка на существование файла java

Проверить, существует ли файл в Java

В этом посте будет обсуждаться, как проверить, существует ли файл в Java.

При проверке существования файла возможны три результата:

  • Файл существует.
  • Файл не существует.
  • Статус файла неизвестен, так как у программы нет доступа к файлу.

Есть несколько способов проверить существование файла в Java. Каждое из следующих решений возвращает true, если файл существует; false в противном случае, когда файл не существует или его статус неизвестен.

1. Использование File.exists() метод

Идея состоит в том, чтобы использовать File.exists() метод, чтобы определить, существует ли файл, обозначенный указанным путем. Этот метод возвращает true, если файл существует; ложно в противном случае.

Обратите внимание, что File.exists() возвращает true, когда ваш путь указывает на каталог. Поэтому рекомендуется вызывать этот метод вместе с File.isDirectory() метод, который проверяет каталог. Это показано ниже:

Обратите внимание, что при работе с томами, смонтированными по NFS, java.io.File.exists иногда возвращается ЛОЖЬ хотя указанный файл действительно существует. См. сведения об ошибке здесь.

2. Использование File.isFile() метод

Мы видели это File.exists() возвращает true, если ваш путь указывает на каталог. Чтобы явно избежать проверки каталога, рекомендуется использовать File.isFile() метод вместо File.exists() метод. File.isFile() метод проверяет, является ли файл, обозначенный указанным путем, обычным файлом, т. е. файл не является каталогом.

3. Использование NIO

Начиная с Java 7, мы можем использовать java.nio.file.Files , который предоставляет несколько статических методов для работы с файлами, каталогами или другими типами файлов. Чтобы просто проверить существование файла, мы можем использовать exists() а также notExists() метод java.nio.file.Files учебный класс. exists() метод возвращает true, если файл существует, тогда как метод notExists() метод возвращает true, если он не существует. Если оба exists() а также notExists() вернуть false, существование файла невозможно проверить. Это может произойти, когда программа не имеет доступа к файлу.

Читайте также:  Тень от границ css

Обратите внимание, что Files.exists() возвращает true, когда ваш путь указывает на каталог. Поэтому рекомендуется использовать этот метод вместе с Files.isDirectory() метод, который проверяет файл на наличие каталога. Это показано ниже:

Источник

Checking a File or Directory

You have a Path instance representing a file or directory, but does that file exist on the file system? Is it readable? Writable? Executable?

Verifying the Existence of a File or Directory

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists, or does not exist. You can do so with the exists(Path, LinkOption. ) and the notExists(Path, LinkOption. ) methods. Note that !Files.exists(path) is not equivalent to Files.notExists(path) . When you are testing a file’s existence, three results are possible:

  • The file is verified to exist.
  • The file is verified to not exist.
  • The file’s status is unknown. This result can occur when the program does not have access to the file.

If both exists and notExists return false , the existence of the file cannot be verified.

Checking File Accessibility

To verify that the program can access a file as needed, you can use the isReadable(Path) , isWritable(Path) , and isExecutable(Path) methods.

The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.

Path file = . ; boolean isRegularExecutableFile = Files.isRegularFile(file) & Files.isReadable(file) & Files.isExecutable(file);

Note: Once any of these methods completes, there is no guarantee that the file can be accessed. A common security flaw in many applications is to perform a check and then access the file. For more information, use your favorite search engine to look up TOCTTOU (pronounced TOCK-too).

Checking Whether Two Paths Locate the Same File

When you have a file system that uses symbolic links, it is possible to have two different paths that locate the same file. The isSameFile(Path, Path) method compares two paths to determine if they locate the same file on the file system. For example:

Path p1 = . ; Path p2 = . ; if (Files.isSameFile(p1, p2)) < // Logic when the paths locate the same file >

Источник

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