I'm relatively new to Java and Netbeans. What I want to do is to topen this Word document file that's inside the package "bloodreports.resources". Location of the document
The reason I'm trying to open it from there specifically is because I think once the runnable JAR file is built, it won't matter where and on which machine I run the JAR file; The resource will always be there.
Is there a better way to do it? Am I wrong?
I've been trying to get this to work for past hour... any help is greatly appreciated!
I tried something along the lines of the following code:
public class WordDocumentHandler {
public static void main(String[]args){
String path = "/resources/bloodreportformat.docx";
File file = new File(path);
if(file.exists()){
System.out.println("Exists");
}
}
}
The word "Exists" never gets printed. What am I doing wrong?
You are trying to access a resource in Netbeans. As @user207421 said, you can't access resources the way you've done, because resources aren't files. You need to use the getResource()
function to solve your problem. Modified code:
public class WordDocumentHandler {
public static void main(String[]args){
String resource_path = "/resources/bloodreportformat.docx";
URL resource_url = WordDocumentHandler.class.getResource(resource_path); //Use this function
//Check if the file exists
if (resource_url != null) {
System.out.println("Exists");
//Other code
}
}
}
The getResource()
function returns a URL of the resource you're trying to access. Once you have the URL, you can access the resource.