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!
Related
so I did run into one very weird issue. The idea is simple: create temp dir, place some files in it and then try to access them. Now the problem is that calling File.createTempDir() or Files.createTempDirectory(prefix) creates new file inside AppData/Local/temp with shortened path, so the full path to folder looks something like C:/Users/FirstNam~1/AppData/Local/Temp/myFolder/myFile.txt instead of C:/Users/FirstName LastName/AppData/Local/Temp/myFolder.myFile.txt.
The difference is that generated path inside java contains FirstNam~1 instead of FistName SecondName. Java then throws exception File Not Found.
When I try to copy and paste shortened path into file explorer I get an error saying that file does not exist, but if I do change shortened path to full one then file opens and it works as intended.
Is there any way to fix it? Ether by forcing java to use full path names or enabling something in windows? I did Enable NTFS long paths policy, but it did not help.
This is happening when using java 8/11 and windows 10 running on VM, project is using AGP and gradle. Temp file is created inside groovy file that extends Plugin<Project>
Just when I lose hope and create a ticket, couple hours after that I find the answer. So, java has method Path.toRealPath() which solves this ~1 issue. After using this method paths no longer contain shortening and are correctly resolved.
EDIT: looks like java is doing everything correct and paths are actually valid, problem did come from library that I'm using and it's a bug with it.
I have a set of codes which are common for two different products, but a part of the code is behaving differently for each product
URL wsdlURL = IntegrationLandscapeService.class.getClassLoader().getResource("IntegrationLandscapeService.wsdl");
For One set up it is giving absolute path and for the other its giving relative path and this is leading to problems, my requirement is to get absolute path for the issue.
Packaging:
Code flow:
The call is made from the Main Class File and from there CommonCode in common code it is looking for the WSDL located in LandScapeService.jar
Update:
The next line of the code is
IntegrationLandscapeService landscapeService = new IntegrationLandscapeService(wsdlURL);
but I get the below error
failed [Failed to access the WSDL at: jar:file:/
tracker.jar!/lib/t24-IF_IntegrationLandscapeService-IntegrationLandscapeService-jwc.jar!/IntegrationLandscapeService.wsdl
.It failed with:
\tracker.jar (The system cannot find the file specified).]
Screen Shot of Jar
The error shows two '!' in the path which indicates the resource is in an embedded/nested/inner jar-file. A product that uses the fat/bundled-jar approach (where one jar-file contains other jar-files) will need some trickery to load classes and resources from the embedded jar-files. You can read about it at http://www.jdotsoft.com/JarClassLoader.php (*)
In any case, there is not much you can do about it since loading resources from embedded jars is not supported natively by Java. The implementation providing the "trickery" I mentioned above will need to fix that (and some do it better than others, see the link above).
The other product with a Par-file indicates the use of OSGi which only requires proper configuration to keep resource-loading working. There is an answer here that explains your situation and solution options.
(*) Spring-boot also has some good documentation and a solution, but I have not tried using the solution with a non-Spring application. See https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html for more information.
You can use getAbsolutePath
File file = new File(url.getPath());
String path = file.getAbsolutePath();
Isn't that what you are looking for?
This is because the files inside the JAR are not treated as regular files, as they are not expanded and not available directly to file explorer.
In Jar, if the files are referred, you will get the path from the root of the JAR file.
Please make sure you have the classpath entry for the Jar location. This will help to find the resource. Otherwise, try the following code(not sure whether it will work in your case, give it a try).
String resource = "/com/example/IntegrationLandscapeService.wsdl"; //package structure of the file
URL res = IntegrationLandscapeService.class.getResource(resource);
Refer this answer to understand more Stack Overflow comment
I am using NetBeans 8.0.2 (I know there already is v8.2 but it has a lot of bugs for me so I got back to v8.0.2) and I need a string path to my .obj file for a parameter attribute like this:
api.parameter("filename", "obj/someFile.obj");
Above example worked in a previous version of my app where I had that .obj file placed in a folder called "obj" in the same directory as my .jar file, but now as I am trying to rather include it in the JAR itself with code:
api.parameter("filename", MyClass.class.getResourceAsStream("/someFile.obj").toString());
...it is not working anymore as the path string interpretation is not a path to a file, it looks more like this:
java.io.BufferedInputStream#215d7ea7
...where, of course, my code is expecting something like normal path string, I would said something in this pseudo-code manner:
api.parameter("filename", "<this.jar>/someFile.obj");
So after a fiddling a bit around StackOverflow I've found pieces of code that I thought could actually enable me to directly place that path as a string:
URL jar = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
api.parameter("filename", jar + "/someFile.obj");
But surprisingly although I checked several times if the file actually really exist in my built jar file (and yes, it is there in the root) it still gives me this error:
java.io.FileNotFoundException: file:\Z:\_JAVA_\MyProject_0_018\dist\bin\myjar.jar\someFile.obj <The filename, directory name, or volume label syntax is incorrect>
And I am 100% sure the name of the file is correct, also its placement in the root of my jar file.
Or does it actually thinks that myjar.jar is a directory?
I am desperately trying to find a solution to this "path string" mess.
Your protection domain's code source location likely returns not what you'd expect it to.
You should use getResource(name) directly, like this:
URL locator = MyClass.class.getResource("someFile.obj");
api.parameter("filename", locator.toString());
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/
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.