Java проверить существует ли директория

How to Check if a File or a Directory Exists in Java

In Java, there are two primary methods of checking if a file or directory exists. These are:

1 — Files.exists from NIO package

2 — File.exists from legacy IO package

Let’s see some of the examples from each package.

Check if File Exists (Java NIO)

The code uses Path and Paths from the Java NIO package to check if a file exists:

import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckFileExist < public static void main(String[] args) < Path path = Paths.get("/path/to/file/app.log"); if (Files.exists(path)) < if (Files.isRegularFile(path)) < System.out.println("App log file exists"); >> else < System.out.println("App log file does not exists"); >> > 

Check if Directory Exists (Java NIO)

Likewise, if we wanted to check if a directory exists in Java using the NIO package:

import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckDirectoryExist < public static void main(String[] args) < Path path = Paths.get("/path/to/logs/"); if (Files.exists(path)) < if (Files.isDirectory(path)) < System.out.println("Logs directory exists"); >> else < System.out.println("Logs directory does not exist"); >> > 

Check if File Exists (Java Legacy IO)

If you’re not using Java NIO package, you can use the legacy Java IO package:

import java.io.File; public class CheckFileExists < public static void main(String[] args) < File file = new File("/path/to/file/app.log"); if(file.exists()) < System.out.println("App log file exists"); >else < System.out.println("App log file does not exist"); >> > 

Check if Directory Exists (Java Legacy IO)

Similarly, to check directory we can use:

import java.io.File; public class CheckFileExists < public static void main(String[] args) < File file = new File("/path/to/logs/"); if(file.isDirectory()) < System.out.println("Logs directory exists"); >else < System.out.println("Logs directory does not exist"); >> > 

Further reading

Источник

Читайте также:  Css html and body height

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 >

Источник

Читайте также:  Ajax request from javascript

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

В этом кратком руководстве мы познакомимся с различными способами проверки существования файла или каталога.

Сначала мы начнем с современных API-интерфейсов NIO, а затем рассмотрим устаревшие подходы к вводу-выводу.

2. Использование java.nio.file.Files ​

Чтобы проверить, существует ли файл или каталог, мы можем использовать метод Files.exists (Path) . Как видно из сигнатуры метода, мы должны сначала получить путь к нужному файлу или каталогу. Затем мы можем передать этот путь в метод Files.exists(Path) :

 Path path = Paths.get("does-not-exist.txt");   assertFalse(Files.exists(path)); 

Поскольку файл не существует, он возвращает false . Также стоит упомянуть, что если метод Files.exists(Path) встречает IOException , он также возвращает false .

С другой стороны, когда данный файл существует, он вернет true , как и ожидалось:

 Path tempFile = Files.createTempFile("foreach", "exist-article");   assertTrue(Files.exists(tempFile)); 

Здесь мы создаем временный файл, а затем вызываем метод Files.exists(Path) .

Это работает даже для каталогов :

 Path tempDirectory = Files.createTempDirectory("foreach-exists");   assertTrue(Files.exists(tempDirectory)); 

Если мы специально хотим знать, существует ли файл или каталог, мы также можем использовать методы Files.isDirectory(Path) или Files.isRegularFile(Path) :

 assertTrue(Files.isDirectory(tempDirectory));   assertFalse(Files.isDirectory(tempFile));   assertTrue(Files.isRegularFile(tempFile)); 

Существует также метод notExists(Path) , который возвращает true , если заданный путь не существует:

 assertFalse(Files.notExists(tempDirectory)); 

Иногда Files.exists(Path) возвращает false , потому что у нас нет необходимых прав доступа к файлам . В таких сценариях мы можем использовать метод Files.isReadable(Path) , чтобы убедиться, что файл действительно доступен для чтения текущему пользователю:

 assertTrue(Files.isReadable(tempFile));   assertFalse(Files.isReadable(Paths.get("/root/.bashrc"))); 

2.1. Символические ссылки​

По умолчанию метод Files.exists(Path) следует символическим ссылкам . Если файл A имеет символическую ссылку на файл B , то метод Files.exists(A) возвращает значение true тогда и только тогда, когда файл B уже существует:

 Path target = Files.createTempFile("foreach", "target");   Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());   Path symbolicLink = Files.createSymbolicLink(symbol, target);   assertTrue(Files.exists(symbolicLink)); 

Теперь, если мы удалим цель ссылки, Files.exists(Path) вернет false :

 Files.deleteIfExists(target);   assertFalse(Files.exists(symbolicLink)); 

Поскольку цель ссылки больше не существует, переход по ссылке ни к чему не приведет, а Files.exists(Path) вернет false .

Можно даже не переходить по символическим ссылкам, передав соответствующий LinkOption в качестве второго аргумента:

 assertTrue(Files.exists(symbolicLink, LinkOption.NOFOLLOW_LINKS)); 

Поскольку сама ссылка существует, метод Files.exists(Path) возвращает значение true. Кроме того, мы можем проверить, является ли путь символической ссылкой, используя метод Files.isSymbolicLink(Path) :

 assertTrue(Files.isSymbolicLink(symbolicLink));   assertFalse(Files.isSymbolicLink(target)); 

3. Использование java.io.File ​

Если мы используем Java 7 или более новую версию Java, настоятельно рекомендуется использовать современные API-интерфейсы Java NIO для таких требований .

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

 assertFalse(new File("invalid").exists()); 

Если файл или каталог уже существует, он вернет true :

 Path tempFilePath = Files.createTempFile("foreach", "exist-io");   Path tempDirectoryPath = Files.createTempDirectory("foreach-exists-io");    File tempFile = new File(tempFilePath.toString());   File tempDirectory = new File(tempDirectoryPath.toString());    assertTrue(tempFile.exists());   assertTrue(tempDirectory.exists()); 

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

Однако метод isFile() возвращает true , если указанный путь является существующим файлом:

 assertTrue(tempFile.isFile());   assertFalse(tempDirectory.isFile()); 

Точно так же метод isDirectory() возвращает true , если указанный путь является существующим каталогом:

 assertTrue(tempDirectory.isDirectory());   assertFalse(tempFile.isDirectory()); 

Наконец, метод canRead() возвращает true , если файл доступен для чтения:

 assertTrue(tempFile.canRead());   assertFalse(new File("/root/.bashrc").canRead()); 

Когда он возвращает false , файл либо не существует, либо текущий пользователь не имеет разрешения на чтение файла.

4. Вывод​

В этом кратком руководстве мы увидели, как убедиться, что файл или каталог существует в Java. Попутно мы говорили о современном NIO и устаревших API-интерфейсах ввода-вывода. Кроме того, мы увидели, как NIO API обрабатывает символические ссылки.

Как обычно, все примеры доступны на GitHub .

Источник

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