Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I open a file inside a package in the Source Packages of Netbeans?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading