AbhishekJoshi
AbhishekJoshi

Reputation: 63

Java and JSF, Checking if a file exists on the server

I have a web application, and I'm trying to return a boolean, of a .zip file that gets (successfully) generated on the server.

Locally I run this on Eclipse with Tomcat on Windows, but I am deploying it to a Tomcat Server on a Linux machine.

        //.zip is generated successfully on the SERVER by this point
        File file1 = new File("/Project/zip/theZipFile.zip");

        boolean exists = file1.exists();// used to print if the file exists, returns false
        if (exists)
            fileLocation = "YES"; 
        else
            fileLocation = "No";

When I do this, it keeps returning false on the debugger and on my page when I print it out. I am sure it has something to do with file paths, but I am unsure.

Once I get the existence of the zip confirmed, I can easily use File.length() to get what I need.

Assume all getters and setters are in existence, and the JSF prints. It is mainly the Java backend I am having a slight issue with.

Thanks for any help! :)

Upvotes: 0

Views: 1853

Answers (2)

Hugues
Hugues

Reputation: 365

Your path is not good. Try remove the leading / to fix the problem See the test code for explanations :

import java.io.*;
public class TestFile {

public static void main(String[] args) {

try {
//Creates a myfile.txt file in the current directory
File f1 = new File("myfile.txt");
f1.createNewFile();
System.out.println(f1.exists());

//Creates a myfile.txt file in a sub-directory
File f2 = new File("subdir/myfile.txt");
f2.createNewFile();
System.out.println(f2.exists());

//Throws an IOException because of the leading /
File f3 = new File("/subdir/myfile.txt");
f3.createNewFile();
System.out.println(f3.exists());

} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}

Upvotes: 1

Chetter Hummin
Chetter Hummin

Reputation: 6817

Debug using this statement

System.out.println("Actual file location : " + file1.getAbsolutePath());

This will tell you the absolute path of the file it's looking for

Upvotes: 0

Related Questions