Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a file from the same package

Tags:

java

I want to open help.chm file when click on the help button. At present , it is opened from the desktop when click help button. I copied and paste the file in one of the packages in my project. Is there a way to open this file from this package?

This is what I did to open the file from desktop

private void helpActionPerformed(java.awt.event.ActionEvent evt)    
{                                            
    try
    {


         Runtime.getRuntime().exec("hh.exe C:/Users/toshiba/Desktop/help2.chm");
    }    
    catch (Exception ex)
    {
        ex.printStackTrace();
        System.out.println(ex.getMessage());
    }            
}         
like image 439
Calm Sea Avatar asked Dec 31 '25 09:12

Calm Sea


2 Answers

Use getResourceAsStream(String name) or getResources(String name) and provide the package name and resource name separated and prefixed by '/'.

For example if the resource is in the package Test:

/Test/help.chm:

Inside the class which you want to access the resource from you'd do (getResourceAsStream(String name)):

InputStream is=getClass().getResourceAsStream("/Test/help.chm");

or using getResources(String name):

URL file=getClass().getResource("/Test/help.chm");

for further help have a look at this great tutorial.

like image 120
David Kroukamp Avatar answered Jan 01 '26 23:01

David Kroukamp


if your file is inside jar package you could get url in this way:

URL resource = getClass().getResource("yourFile.chm");
System.out.println("URL to resource: " + resource );

or you can try something like:

//it return the relative path 

ResourcesLoader.class.getClassLoader().getResource("package1/resources/repository/yourFile.chm").toString(); // if file is inside package
like image 22
Jayyrus Avatar answered Jan 01 '26 22:01

Jayyrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!