How to Check If a File Exists in Java

How do I check if a file exists in Java?

Using java.io.File:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}

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

You can test whether a file or directory exists using the Java File exists() method.

File file = new File("/temp.txt");
boolean cond1 = file.exists();

The method will return true when the file or directory is found and false if the file is not found.

You can also use the Files.exists() and Files.notExists() Java methods if that is easier too.

There are also the constants Constants.FILE_EXISTS and Constants.FILE_EXISTS you can use to test conditions.

Check if file exists without creating it

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.

Check if file exists on server and return that file content

File.exists() checks the file existence with the file-system, and so it should behave like a volatile, so you are covered there

Some issues though -

1) As soon as a thread sees that the file doesn't exist, it starts downloading the file, which is time consuming, so its likely that other threads will also come and start downloading the same file. So the download part should be moved inside the lock

2) You're renaming the temp file outside the lock. A thread may get to that point without creating/writing-to a temp file. Should move the rename inside the lock as-well

Since IO has much more overhead than locking, I think the above 2 steps would be beneficial

Check if file exists in a folder

  File file = new File("three_v1_FVID121007.jpg");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}

How to check if a file exists while using a Scanner in Java

To check whether the file or directory denoted by provided pathname exists you can use exist() :

public static void main(String[] args) {
final File file = new File("temp/foo.txt");
if (file.exists()) {
System.out.printf("File " + file.getName() + " exist !");
}
}

Not let's take a look at our Scanner :

public Scanner(File source) throws FileNotFoundException {}

If you pass a file to the Scanner which does not exist - you will get an exception.

So to ensure that file exists in this case you can :

public static void main(String[] args) {
// let's say there is no such file
final File file = new File("temp/foo.txt");
try {
Scanner scanner = new Scanner(file); // this will fail if file does not exist
// otherwise it exist and you can do what you want
} catch (FileNotFoundException e) {
// and here you can handle the case when file not exist
}
}

If you mean how to check if your scanner can fetch something, scanner has a lot of hasNext... methods. Like hasNext(), hasNextByte(), hasNextLine(), etc.

And before you do scanner.next() you should check! e.g. :

if (scanner.hasNext()) {
String fileAccess = scanner.next();
}

These lines in your code are wrong because you try to check if 2 different types String and Scanner are equals(). They never are.

// fileAccess is String and fileName is Scanner according to your code
if(fileAccess.equals(fileName)) {
System.out.print("Well this file exists, but I don't know how to make it into a scanner");
}

How I would rewrite your piece of code (but not sure I understand what exactly it should do), so just as an example:

public static void createdChoice() throws FileNotFoundException {
File madLibFile = new File("/Users/adanvivero/IdeaProjects/Assignment 4/src/mymadlib.txt");
if (madLibFile.exist()) {
Scanner inScanner = new Scanner(System.in);
Scanner fileScanner = new Scanner(madLibFile);
System.out.println("Input file name: " + madLibFile.getName());
if (inScanner.hasNext()) {
String fileAccess = inScanner.next();
// do whatever you need e.g
if(fileAccess.equals(madLibFile.getName())) {
// something here
}
} else {
System.out.println("No more tokens to read !");
}
} else {
System.out.println("File mymadlib.txt does not exist !");
}
}

Hope this is somehow helpful.

Happy hacking :)

checking if file exists in a specific directory

Do you expect temp.MOD file to be in the current directory (the directory from which you run your application), or you want it to be in the "directory" folder? In the latter case, try creating the file this way:

boolean check = new File(directory, temp).exists();

Also check for the file permissions, because it will fail on permission errors as well. Case sensitivily might also be the cause of the issue as Spaeth mentioned.

Check if file exists based on partial file name in Java

This code should help you.

First list out all the files in the folder

Start a loop and then get the fileName for each file and start
comparing the name to do your job.

String folderName = "."; // Give your folderName
File[] listFiles = new File(folderName).listFiles();

for (int i = 0; i < listFiles.length; i++) {

if (listFiles[i].isFile()) {
String fileName = listFiles[i].getName();
if (fileName.startsWith("MyTextFile_")
&& fileName.endsWith(".txt")) {
System.out.println("found file" + " " + fileName);
}
}
}


Related Topics



Leave a reply



Submit