简体   繁体   中英

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! :)

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());
}
}
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM