Java if dir exists

Check If a File or Directory Exists in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Читайте также:  Python tutorial if not

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’re going to get familiar with different ways to check the existence of a file or directory.

First, we’ll start with the modern NIO APIs and then will cover the legacy IO approaches.

2. Using java.nio.file.Files

To check if a file or directory exists, we can leverage the Files.exists(Path) method. As it’s clear from the method signature, we should first obtain a Path to the intended file or directory. Then we can pass that Path to the Files.exists(Path) method:

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

Since the file doesn’t exist, it returns false. It’s also worth mentioning that if the Files.exists(Path) method encounters an IOException, it’ll return false, too.

On the other hand, when the given file exists, it’ll return true as expected:

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

Here we’re creating a temporary file and then calling the Files.exists(Path) method.

This even works for directories:

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

If we specifically want to know if a file or directory exists, we can also use Files.isDirectory(Path) or Files.isRegularFile(Path) methods:

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

There is also a notExists(Path) method that returns true if the given Path doesn’t exist:

assertFalse(Files.notExists(tempDirectory));

Sometimes the Files.exists(Path) returns false because we don’t possess the required file permissions. In such scenarios, we can use the Files.isReadable(Path) method to make sure the file is actually readable by the current user:

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

By default, the Files.exists(Path) method follows the symbolic links. If file A has a symbolic link to file B, then the Files.exists(A) method returns true if and only if the file B exists already:

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

Now if we delete the target of the link, the Files.exists(Path) will return false:

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

Since the link target doesn’t exist anymore, following the link won’t lead to anything, and Files.exists(Path) will return false.

It’s even possible to not follow the symbolic links by passing an appropriate LinkOption as the second argument:

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

Because the link itself exists, the Files.exists(Path) method returns true. Also, we can check if a Path is a symbolic link using the Files.isSymbolicLink(Path) method:

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

3. Using java.io.File

If we’re using Java 7 or a newer version of Java, it’s highly recommended to use the modern Java NIO APIs for these sorts of requirements.

Читайте также:  Program written in java language

However, to make sure if a file or directory exists in Java legacy IO world, we can call the exists() method on File instances:

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

If the file or directory does exist already, it’ll return true:

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

As shown above, the exists() method doesn’t care if it’s a file or directory. Therefore, as long as it does exist, it’ll return true.

The isFile() method, however, returns true if the given path is an existing file:

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

Similarly, the isDirectory() method returns true if the given path is an existing directory:

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

Finally, the canRead() method returns true if the file is readable:

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

When it returns false, the file either doesn’t exist or the current user doesn’t possess the read permission on the file.

4. Conclusion

In this short tutorial, we saw how to make sure a file or directory exists in Java. Along the way, we talked about modern NIO and the legacy IO APIs. Also, we saw how the NIO API handles symbolic links.

As usual, all the examples are available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

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 >

Источник

How to check if a directory exists in Java

In the previous article, we looked at how to check if a regular file exists in Java. In this short article, you’ll learn how to check if a directory exists in the file system using Java.

In Java 7 and higher, you can use the NIO API Files.isDirectory() static method to check if a folder exists in your file system:

if (Files.isDirectory(Paths.get("/var/lib/")))  System.out.println("Directory found."); > else  System.out.println("Directory not found."); > 

To make sure that the directory is not a symbolic link, you can pass LinkOption.NOFOLLOW_LINKS :

if (Files.isDirectory(Paths.get("/var/lib/"), LinkOption.NOFOLLOW_LINKS))  System.out.println("Directory found."); > else  System.out.println("Directory not found."); > 

In Java 6 or below, you can use File.isDirectory() method to check for directory existence in Java as shown below:

File file = new File("/var/lib/"); // check if directory exists if (file.isDirectory())  System.out.println("Directory found."); > else  System.out.println("Directory not found."); > 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

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