This question already has answers here:
How do I read a resource file from a Java jar file?
(9 answers)
Closed 9 years ago.
I know it seems like my question has been answered before, but I can't find an answer for my case.
What I am trying to do, is to get a File type from resource, so when it's packaged, it can be accessed. The answers I found were trying to read that file, but what I really need, is to construct a File object, because I have a third party library that is expecting that object.
Here is a the code I tried:
String xslFilePath = new Test().getClass().getResource("/com/test/decision_template.xsl").getPath();
System.out.println(xslFilePath);
File xsltfile = new File(xslFilePath);
System.out.println(xsltfile.getAbsolutePath()+", exist:"+xsltfile.exists());
I got this result:
C:\>java -jar test.jar
file:/C:/test.jar!/com/test/decision_template.xsl
C:\\file:\C:\test.jar!\com\test\decision_template.xsl, exist:false
java.io.FileNotFoundException: file:\C:\test.jar!\com\test\decision_template.xsl
(Syntaxe du nom de fichier, de rÚpertoire ou de volume incorrecte)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at com.test.Test.main(Test.java:30)
I need a way to get that file so the .exists() return true.
You can try the TrueZip library. It's quite good. I believe you'll need to implement your own DirectoryScanner or something.
Better yet, just knock up an implementation of your own which scans through all the jars on your classpath. Here's an example of how I've done it in one of my projects on GitHub. I think that you could easily tailor it to suit your needs.
Have fun! :)
Related
This question already has an answer here:
Any way to get a File object from a JAR
(1 answer)
Closed 5 years ago.
I'm trying to implement a button into my project which, when clicked, automatically loads a specific file. Currently there are buttons for users selecting a file from their hard disk.
So, I downloaded the specific file and inserted it into the project. When using File f = new File("demofile") or something like this
getClass().getResource("/resources/file.txt").getFile(); the code WORKS locally.
However, when the project is packaged, a FileNotFoundException is thrown.
After much research online, there are suggestions to use something like:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
However, for this project, I need the file to be referenced as a file object so that it can be passed as an argument to other functions, such as:
in = new TextFileFeaturedSequenceReader(TextFileFeaturedSequenceReader.FASTA_FORMAT, file, DiffEditFeaturedSequence.class);
Any ideas on how I can solve this, or read a stream into a file object?
Thanks!
If you absolutely must pass a File, copy your resource to a temporary file:
Path path = Files.createTempFile(null, null);
try (InputStream stream =
getClass().getResourceAsStream("/resources/file.txt")) {
Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
}
in = new TextFileFeaturedSequenceReader(
TextFileFeaturedSequenceReader.FASTA_FORMAT,
path.toFile(),
DiffEditFeaturedSequence.class);
// Use the TextFileFeaturedSequenceReader as needed
// ...
Files.delete(path);
This question already has answers here:
Java Paths.get .... readAllBytes(path)) not working with relative path
(2 answers)
Java isn't getting the file in the source code when compiled
(2 answers)
Closed 5 years ago.
I have an input file data, name input.dat which is stored in the src/main/resources. When I tried to read from this input file as follows:
String[] lines = Files.readAllLines(new File("input.dat").toPath()).toArray(new String[0]);
I received the following exception:
java.nio.file.NoSuchFileException: input.dat
Can anyone help me with what did I do wrong here? Thank you in advance!
The java file you are running is probably not in the same directory as the file input.dat.
When referencing the file in your Java code include the relative path to it. If the java file that you are running is in src/main then the relative path would be resources/input.dat.
In that case, your code would look like this:
String[] lines = Files.readAllLines(new File("resources/input.dat").toPath()).toArray(new String[0]);
Hope this helped you and if you have any further questions please feel free to post a comment below!
Replace input.dat with the exact path of input.dat. Such as C:/Users/Soe/Desktop/input.dat
This question already has answers here:
getClass().getResource() always returning null
(5 answers)
Closed 8 years ago.
I am trying to export an image inside my runnable jar. After some research i have come across this method:
ImageIO.read(getClass().getClassLoader().getResource("image path"));
After following several response and looking at the API, i have attempted this myself. My current directory set up is as follows:
This is my code:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("/res/cherry.png"));
which is being called from the Snake.java source file.
This is the error message:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at cje.chris.edwards.snake.game.Snake.<init>(Snake.java:51)
at cje.chris.edwards.snake.game.Snake.main(Snake.java:156)
Snake.java:51 is the line of code posted above. I understand this is because it cannot find the resource, what am i doing wrong? I have added the res folder to my build path.
I have also tried:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("res/cherry.png"));
This produces the same error message.
Answer:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("cherry.png"));
Thanks.
I think your problem is the leading "/"
"/res/cherry.png"
Will make it an absolute path (from your root of your drive) not a relative path from your starting from the root of your jar
Making it "res/cherry.png" should work
This question already has answers here:
What is meant by immutable?
(17 answers)
Closed 3 years ago.
The question says it all.
I have a File object which is pointing to /home/user/filename1.
If I call file.getAbsolutePath() then it would return /home/user/filename1
My question is that -
Can we change the path inside file object to a different location?
If yes, then how?
Thanks
"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. "
From the File javadoc.
I had developed a code to rename the file and I have to save the file in the same location recursively. I think the below code helps you out upto some extent. I have to replace "-a" in my filename and save it in the same folder. If needed in place of "destPath" you can give the destination path of your string path. I think this might help you.
File oldfile =new File(file.getAbsolutePath());
String origPath = file.getCanonicalPath();
String destPath = origPath.replace(file.getName(),"");
String destFile = file.getName();
String n_destFile = destFile.replace("-a", "");
File newfile =new File(destPath+n_destFile);
A file is internally nothing else other then a string holding the path to the file. So no this is not possible. Why would you even want to do something like this? Unless you have moved the file to another location?
As someone noted before, File is immutable as many of java API classes. Maybe what you want is to copy a file from somewhere to some other place? Have in mind that a File object has no actual binding to the contents of the file, and will not allow you modifying or moving it.
Have a look at Apache Commons IO
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
Here you have a useful library to deal with files.
First:
I know, this question was asked about 100 times already.
I know, someone already could have gave the right answer.
But anyway, I have to ask this again. I didn't found a solution working for me. sorry.
I'm writing a game in java. Of course I have many packages (folders) with sounds and pictures and so on. But these folders are each of variable size. So I want to save the content of such a folder dynamically in a list.
Usually, I was making this:
File f[] = new File(getClass.getResource("/home/res/").toURI()).listFiles();
Now I can iterate though this file object and save each file. Perfect. Really?
No. When I extract this Project into a jar archive, this fails. All because a uri isn't "hierarchical" or some stuff like this. See this exception:
C:\Users\Administrator\Desktop>java -jar Homework.jar
java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(Unknown Source)
at homework.moonface.src.Moonface.loadSounds(Moonface.java:94)
at homework.moonface.src.Moonface.<init>(Moonface.java:55)
at control.Overview.main(Overview.java:16)
Ok, I thought, so I need to get this path and add it manual into the file object. (new File("path"); But... this doesn't work. I'm getting the known error that the input wasn't written correctly, or when i try to cut of "file:" from the resource url, it breaks because in a jar its "jar:file:" and not "file:". But also if I cut of jar:file: I'm getting null.
So, please don't mark this as a duplicate, and try to explain this shortly for me. It would help thousand other, who don't understand other solutions who aren't solutions.
Try this :
URL jarResourceURL = getClass().getResource("/home/res/");
JarURLConnection jarURLConnection = (JarURLConnection) jarResourceURL.openConnection();
Enumeration<JarEntry> entries = jarURLConnection.getJarFile().entries();
while (entries.hasMoreElements()){
entries.nextElement(); // iterate over entries and do something
}
UPD: I was thinking about how spring framework's ClassPathXmlApplicationContext resolves the resources from jars. So i investigated the source code and foud that there is an utility class org.springframework.core.io.ClassPathResource which have a convenient interface (moreover there is a possibility to get the corresponding java.io.File instance using it) and can help you to solve the problem. Here is the doc :
http://docs.spring.io/spring/docs/2.5.x/api/org/springframework/core/io/ClassPathResource.html