Java check is file exist

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.

Читайте также:  What is ecj java

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 >

Источник

Проверить, существует ли файл в 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, существование файла невозможно проверить. Это может произойти, когда программа не имеет доступа к файлу.

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

Источник

Java: Check if a File or Directory Exists

Checking if a file or directory exists is a simple and important operation in many tasks. Before accessing a file, we should check if it exists to avoid a NullPointerException . The same goes for directories.

While some functions may create a new file/directory if the requested one doesn’t exist, this may be the opposite of what we want. If we wish to append more information to an existing file and the method goes through without a warning, since it creates the new file it needs — we may have lost some information without realizing it.

Here, we’ve got a simple structure:

02/13/2020 11:53 AM directory 02/13/2020 11:55 AM directory_link [directory] 02/13/2020 11:53 AM 0 file.txt 02/13/2020 11:55 AM symlink.txt [file.txt] 

There’s a file.txt file and a symlink.txt file. The symlink.txt file is a symbolic link to the file.txt .

Similarly, we’ve got a directory and a symbolic link to it — directory_link .

Check if a File Exists

To work with the Files class, you need to be acquainted with the Path class. Files only accepts Path , and not File objects.

For the purposes of the tutorial, we’ll define a File and Path instance for the file.txt in our directory:

final static String location = "C:\\file.txt"; Path path = Paths.get(location); File file = new File(location); 

Files.exists()

That being said, the first way we can check if a file exists is through the Files class:

// Check if file exists through a Path System.out.println(Files.exists(path)); // Check if a file exists by converting File object to Path System.out.println(Files.exists(file.toPath())); 

Running this code will yield us:

Files.notExists()

You might be wondering why the notExists() method exists at all:

If exists() returns true , that means that notExists() should return false . They’re logical complements and A = !B , right?

Well, that’s where many get it wrong. If Files.exists() returns false , it doesn’t have to mean that the file doesn’t exist.

It can also mean that the file’s existence cannot be verified. In that case, both Files.exists() and Files.notExists() would return false , as Java cannot determine if the file does or doesn’t exist.

This typically happens if you have a file that’s locked in a way that Java can’t access it. Imagine we had a file that’s locked in our directory — lockedFile.txt :

And if we tried verifying its existence with:

System.out.println(Files.exists(path)); System.out.println(Files.notExists(path)); 

It exists, obviously, but Java doesn’t have permission to confirm that on our system — thus giving conflicting results.

Files.isRegularFile()

Additionally, we can check if the file is a regular file ( false if it’s a directory) through the isRegularFile() method:

System.out.println(Files.isRegularFile(path)); 

File.isFile()

Instead of using the Files class, we can also perform methods on the file objects themselves:

System.out.println(file.isFile()); 

File.exists()

Similar to the previous option, we can run the exists() method:

System.out.println(file.exists()); 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The difference between these two is that the first one checks if it’s a file, and the other one checks if it exists. In different circumstances, they’d return different results.

Locked Files

A fun thing to note is that if you’re using a File to check for existence, Java can determine if the locked file from before exists or not:

System.out.println(file.isFile()); System.out.println(file.exists()); 

Running this piece of code will yield:

With this, it’s evident that the locked file can be read by using the File class instead of the Files helper class.

Check if a Directory Exists

Directories are essentially files, that can contain other files. This is why checking if a directory is a file will return true . Though, if you’re checking if a directory is a directory (a special type of file), you’ll get a more accurate result.

This time around, we’re switching our location to:

final static String location = "C:\\directory"; 

Files.exists()

Again, just like in the first example, we can check if it exists via:

System.out.println(Files.exists(path)); 

Files.isDirectory()

If we’d like to check if it’s specifically a directory, we’d use:

System.out.println(Files.isDirectory(path)); 

Note: If the directory doesn’t exist, the isDirectory() method will return false . It’s due to the way the method is named. What it does is — it checks if the file exists and if it’s a directory, not only the latter. A file can’t be a directory if it doesn’t exist — hence, false is returned.

You might also want to check if a file is just a symbolic link. In that case, you’d use the Files class.

Let’s switch our location to:

final static String location = "C:\\symlink.txt"; 

As usual, the Files class accepts a Path to the file:

System.out.println(Files.isSymbolicLink(path)); 

File.getCanonicalPath() vs File.getAbsolutePath()

Another way to check for a symbolic link is to compare the results of the file’s canonical path and absolute path. If they’re different, it’s most probably a symbolic link:

System.out.println(file.getCanonicalPath()); System.out.println(file.getAbsolutePath()); 

Since we’re checking for a symbolic link, and we know it is, these should return a different result — a symlink.txt and file.txt path:

However, this isn’t the case here. This is due to the fact that the symlink was created on Windows with NTFS (New Technology File System). The symlink was created using the mklink command in the CMD.

Check if Either Exist

From the previous examples, it’s evident that the Files.exists() method will return true for both existing files and directories. Though, it doesn’t work best when it comes to locked files.

On the other hand, the exists() method from the File class will also return true for both files and directories and can read the locked file that the Files class can’t.

Conclusion

Checking for the existence of files and directories is the first line of defense against missing files and directories. Different approaches have different setbacks and you might assume that a method will return an accurate result, but it won’t due to how it works in the background.

Being aware of which methods return which results in which circumstances will allow you to avoid nasty exceptions when handling files.

After checking if your file exists or not, you’ll likely want to do some Reading and Writing Files in Java.

Источник

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