Regarding Help File in JAVA - java

I'm new to help file creation in java. I have created a help file "sample.chm" with a 3rd party tool, added it to a java program with package name as "help" calling with runtime class and build the jar. When I run the jar file it is giving me an error that the "file cannot be found, null pointer Exception". I have given a relative path to identify the file like "../help/sample.chm" still it is not working and I tried with various classes to ientify the path. But still the same error.
Request you to please help me in fixing it.
The jar can be placed in different systems and should open this help file with out any issues.
I hope my explanation is sufficient you to identify the problem.
Regards,
Chandu

If you have a file inside a jar, you can't access it as you normally would. You can access it like this:
URL helpFile=Thread.currentThread().getContextClassLoader().getResource("help/sample.chm");
The method used above (getResource) will return a URL; if you want, you can get it as an InputStream as well by using getResourceAsStream instead.

At least a workaround unless a better solution pops up. Use the this.getClass().getClassLoader().getResource way to get an inputstream to the help file inside the jar.
Copy the bytes to a new help file in the target systems temp folder and use this extracted file with the external help file viewer.

Related

java.nio.file.InvalidPathException with getPath

I am using this code
String path = getClass().getResource("Template.xls").getPath();
When I run it on my machine (windows), everything is good. I even did system.out.println on the get resource part and on the get path part and the results were:
file:/C:/Eclipse/Netbeans/SoftwareCom/build/classes/assets/Template.xls
/C:/Eclipse/Netbeans/SoftwareCom/build/classes/assets/Template.xls
However I am getting the following error reports from some users
java.nio.file.InvalidPathException: Illegal char <:> at index 4:
file:\C:\Software%20Com\SoftwareCom.exe!\assets\Template.xls
Iam not sure whats happening or why would it work for some and not others
Any pointers?
To answer this question properly, it would be helpful to know what you want to do with the path information. To read the file, you don't need the path.
You could just call
getClass().getResourceAsStream("Template.xls")
If you really want to know the path, you should call
URL url = getClass().getResource("Template.xls");
Path dest = Paths.get(url.toURI());
This might cause problems as you seem to pack your java files in a windows executable. See Error in URL.getFile()
Edit for your comment:
As I wrote above, you don't need the path of the source to copy. You can use
getClass().getResourceAsStream("Template.xls")
to get the content of the file and write the content to whereever you want to write it. The reason for failing is that the file in your second example is contained within an executable file:
file:\C:\Software%20Com\SoftwareCom.exe
as can be seen from the path:
file:\C:\Software%20Com\SoftwareCom.exe!\assets\Template.xls
The exclamation mark indicates that the resource is within that file.
It works within Netbeans because there the resource is not packed in a jar, but rather is a separate file on the filesystem.
You should try to run the exe-version on your machine. It will most likely fail as well. If you want more information or help, please provide the complete code.
I faced this same issue and go around it by using the good ol' File API
URL url = MyClass.class.getClassLoader().getResource("myScript.sh");
Path scriptPath = new File(url.getPath()).toPath();
And it worked!

Why does getResourceAsStream() work in the IDE but not the JAR?

I just want to read a file into my program. The file is located one directory above the working directory at "../f.fsh". So the following code runs correctly when I run it in the IDE
String name="../f.fsh";
InputStream is = getClass().getResourceAsStream(name);
InputStreamReader isreader=new InputStreamReader(is);//CRASHES HERE WITH NULL POINTER EXCEPTION
BufferedReader br = new BufferedReader(isreader);
but when I create a JAR file that has f.fsh zipped inside of it and run it, it crashes when creating the InputStreamReader, because the InputStream is null.
I've read a bunch of answers to questions about input streams and JAR files, and what I got out of it is that I should be using relative paths, but I am already doing that. From what I understand getResourceAsStream() can find files relative to the root of the project, that is what I want. Why does it not work in the JAR? What is going wrong, how can I fix it?
Does it have to do with the classpath? I thought that was only for including files external to the jar being run.
I have also tried, but still fail, when putting a slash in:
InputStream is = getClass().getResourceAsStream("\\"+name);
I looked at: How to get a path to a resource in a Java JAR file andfound that contents of a JAR may not necesarily be accesible as a file. So I tried it with copying the file relative to the jar (one directory up from the jar), and that still fails. In any case I'd like to leave my files in the jar and be able to read them there. I don't know what's going wrong.
You can't use .. with Class.getResourceAsStream().
To load a resource f.fsh in the same package as the class, use SomeClass.class.getResourceAsStream("f.fsh")
To load a resource f.fsh in a sub-package foo.bar of the package of the class, use SomeClass.class.getResourceAsStream("foo/bar/f.fsh")
To load a resource f.fsh in any package com.company.foo.bar, use SomeClass.class.getResourceAsStream("/com/company/foo/bar/f.fsh")
This is described in the javadoc of the getResource() method, although it lacks examples.
If .. works in Class.getResourceAsStream() while running from Eclipse, it's a bug in Eclipse. Eclipse and other IDEs implement custom class loaders to fetch resources from the project at runtime. It looks like the class loader implementation in Eclipse isn't performing all the necessary validations on input to getResourceAsStream() method. In this case the bug is in your favor, but you will still need to rethink how you structure your resources for your code to work in all cases.
it's mandatory that the name of the file is CASE SENSITIVE
it's mandatory to refresh (F5) the project explorer if the file is moved or copied outside Exclipse

ClassLoader loading the wrong instance of a file

So I see there has already been a post very similar to this issue, however I am in a situation where I have no power to specify the location of this file within my jar and so am hoping someone is aware of a solution to get around this.
So I currently use the following snippet to obtain a file as an input stream, the file 'plugin.xml' is located at the root of the jar and I cannot change this location as another piece of software (dynatrace) creates this file and determines its location.
the standard snippet:
InputStream is = JmxPlugin.class.getResourceAsStream("/plugin.xml");
Now I am aware that the issue is that the ClassLoader is picking up the first file which matches the name 'Plugin.xml' along the classpath (one which isn't in my jar, yay).
Can anyone think of a way to ensure I pick up the correct file without having to move it? The relative path of my class in the jar is com/something/jmx/JmxPlugin.class.
(Id rather not have to unpack the jar in memory).
Many thanks for any contributions,
I'm not absolutely sure, but seems like Thread.currentThread().getContextClassLoader().getResourceAsStream("/plugin.xml") may solve your issue. If not, you'll have to create your own ClassLoader and resolve the issue there.
The simplies way is to move your jar in classpath to be the first containing Plugin.xml,
Another approach is to use getResource() to locate your jar file:
URL myJar=JmxPlugin.class.getResource("/"+JmxPlugin.class.getName().replace(".","/")+".class");
then use this URL to open jar file and extract Plugin.xml.

Path resolution in eclipse package structure

This is a very simple question for many of you reading this, but it's quite new for me.
Here is a screenshot for my eclipse
When i run this program i get java.io.FileNotFoundException: queries.xml (The system cannot find the file specified) i tried ../../../queries.xml but that is also not working. I really don't understand when to use ../ because it means go 1 step back in dir, and in some cases it works, can anyone explain this? Also how can I refer to queries.xml here. Thanks
Note: I might even use this code on a linux box
I assume it is compiling your code into a build or classes folder, and running it from there...
Have you tried the traditional Java way for doing this:
def query = new XmlSlurper().parse( GroovySlurping.class.getResourceAsStream( '/queries.xml' ) )
Assuming the build step is copying the xml into the build folder, I believe that should work
I don't use Eclipse though, so can't be 100% sure...
Try
file = new File("src/org/ars/groovy/queries.xml");
To check the actual working directory of eclipse you can use
File f = new File(".");
System.out.println(f.getAbsolutePath());
You could try using a property file to store the path of the xml files.
This way you can place the xml files in any location, and simply change the property file.
This will not require a change/recompilation of code.
This would mean you will only need to hardcode the path of the property file.
If you prefer not hardcoding the path of the property file, then you could pass it as an argument during startup in your server setup file. (in tomcat web.xml). Every server will have an equivalent setup file where you could specify the path of the property file.
Alternatively you could specify the path of the xml in this same file, if you don't want to use property files.
This link will show you an example of reading from property files.
http://www.zparacha.com/how-to-read-properties-file-in-java/

Netbeans Built .jar doesn't work with class file inside

I had problems while finding the path of file(s) in Netbeans..
Problem is already solved (checked answer).
Today I noticed another problem: When project is finished,
I have to execute the generated .jar to launch the program, but it doesn't work because an error occurs: NullPointer (where to load a file) when accessing/openning jar outside Netbeans.
Is it possible to open a file with the class file in Java/Netbeans which works in Netbeans and even in any directory?
I've found already some threads about my problem in site but none was helpful.
Code:
File file = new File(URLDecoder.decode(this.getClass().getResource("file.xml").getFile(), "UTF-8"));
The problem you have is that File only refer to files on the filesystem, not files in jars.
If you want a more generic locator, use a URL which is what getResource provides. However, usually you don't need to know the location of the file, you just need its contents, in which case you can use getResourceAsInputStream()
This all assumes your class path is configured correctly.
Yes, you should be able to load a file anywhere on your file system that the java process has access to. You just need to have the path explicitly set in your getResource call.
For example:
File file = new File(URLDecoder.decode(this.getClass().getResource("C:\\foo\\bar\\file.xml").getFile(), "UTF-8"));

Categories

Resources