26

If I do this:

File f = new File("c:\\text.txt");

if (f.exists()) {
    System.out.println("File exists");
} else {
    System.out.println("File not found!");
}

Then the file gets created and always returns "File exists". Is it possible to check if a file exists without creating it?

EDIT:

I forgot to mention that it's in a for loop. So here's the real thing:

for (int i = 0; i < 10; i++) {
    File file = new File("c:\\text" + i + ".txt");
    System.out.println("New file created: " + file.getPath());
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • possible duplicate of [How do I check if a file exists? (Java on Windows)](http://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-java-on-windows) – MarcoS Jul 02 '12 at 10:26
  • 1
    @MarcoS: actually it's not a duplicate. The title of this question is simply badly phrased. – Joachim Sauer Jul 02 '12 at 10:28
  • @JoachimSauer: maybe it's not an exact duplicate, but the answer could be infer by reading that question and trying a little bit of code ... so for me it's a duplicate – MarcoS Jul 02 '12 at 11:59
  • Can you but any method in to a WEBMethods transformer? I need to do exaclty what this code does. – Doug Hauf Jan 24 '14 at 19:01

4 Answers4

54

When you instantiate a File, you're not creating anything on disk but just building an object on which you can call some methods, like exists().

That's fine and cheap, don't try to avoid this instantiation.

The File instance has only two fields:

private String path;
private transient int prefixLength;

And here is the constructor :

public File(String pathname) {
    if (pathname == null) {
        throw new NullPointerException();
    }
    this.path = fs.normalize(pathname);
    this.prefixLength = fs.prefixLength(this.path);
}

As you can see, the File instance is just an encapsulation of the path. Creating it in order to call exists() is the correct way to proceed. Don't try to optimize it away.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 5
    @ThreaT: contrary to common opinion, running code inside a loop does **not** fundamentally change what the code does. – Joachim Sauer Jul 02 '12 at 10:26
  • 1
    @ThreaT if the `new File` code is in a loop, you might be guilty of inefficient coding, but it still won't create a real file. If your file exists, it's absolutely not due to the File class. – mah Jul 02 '12 at 10:27
  • @ThreaT There is no worry. Seriously, that's really cheap. That's not really more than an encapsulation of your path. – Denys Séguret Jul 02 '12 at 10:27
  • @ThreaT: no, it does not. `new File()` never *creates* a file on the file system, no matter where it is. *Something else* in your loop might create that file, however. – Joachim Sauer Jul 02 '12 at 10:27
  • 2
    @ThreaT: that code **still** doesn't create files on your hard disk, *unless* it's *not* `java.io.File` you're talking about. Is there any other class named `File` anywhere in your project that you might (accidentally) be using? – Joachim Sauer Jul 02 '12 at 10:35
  • what is "fs" in this.path = fs.normalize(pathname); ? – Dinith Rukshan Kumara Apr 02 '18 at 15:03
12

Starting from Java 7 you can use java.nio.file.Files.exists:

Path p = Paths.get("C:\\Users\\first.last");
boolean exists = Files.exists(p);
boolean notExists = Files.notExists(p);

if (exists) {
    System.out.println("File exists!");
} else if (notExists) {
    System.out.println("File doesn't exist!");
} else {
    System.out.println("File's status is unknown!");
}

In the Oracle tutorial you can find some details about this:

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
11

Creating a File instance does not create a file on the file system, so the posted code will do what you require.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • @ThreaT, totally irrelevant. In order to create a file using `File` you need to invoke `File.createNewFile()`. – hmjd Jul 02 '12 at 10:29
  • @ThreaT, that `for` loop will not create files. It will print out the message "New file created ...." but this files will not exist on your file system. Add `file.exists()` to your message and it will be `false` (assuming they do not currently exist). – hmjd Jul 02 '12 at 10:37
3

The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.

This can be applied too for Files.noExists, Files.isDirectory and Files.isRegularFile

According this you can use the following :

Paths.get("file_path").toFile().exists()
Kelevra
  • 71
  • 2