I am trying to upload files by ftp using the apache common library. I want to keep those file inside the jar, since these are files that will stay the same and need to be uploaded on the different hosts several time.
I am trying the following:
public void doCGIRecovery() throws IOException{
System.out.println(getClass().getResource("/cgi/example").getPath());
FileInputStream file = new FileInputStream(getClass().getResource("/cgi/example").getPath());
f.storeFile("./", file);
}
Using eclipse this works and the sysout is giving me:
/Users/user/Documents/workspace/example-Project/bin/com/example/java/example/business/cgi/example
But after the compilation into a jar it returns me the following:
file:/Users/user/Desktop/example.jar!/com/example/java/example/business/cgi/example
And I get (No such file or directory).
So how does that come? Further where does the "!" after example.jar come from?
Best Regards
Don't worry about messing with the path, use getClass().getResourceAsStream() instead.
Related
How do you store a file inside a jar library?
Setup :
Create a simple maven project with a class that loads something from the resources folder using the getResoruceAsStream() method and a test that runs it. The test will fail with the problem being it couldn't find that file, the same issue will appear later when we try to compile it as a lib and run that class.
The problem : Using the only method I know (and the only that you can find on the web) getResourceAsStream() will give you a null reference exception, because the file is missing. So how do I add the file to the jar and load it later?
Keep the file in the src/main/resources directory and use the following method in the class where you need to load that file -
private InputStream readFileFromResourcePath(String filename) {
return getClass().getClassLoader().getResourceAsStream(filename);
}
Do not forget to close the stream after consuming it.
I am trying to execute a windows command inside java code using Runtime.exec() command. It is working fine when put all the necessary batch file and properties file on the root directory. But when i am exporting this is as jar, the java program is throwing error, which is becuase it is not able to find all those dependent .bat and .properties files. Can some one please tell me, where should i keep all the .bat and .properties files in side the folder. Thanks in Advance.
You can do so
Something like
Runtime.getRuntime().exec("cmd /c start yourFile.bat");
You should be able to keep it in the root of your jar if you want
EDIT :
On second thought I don't think you can run bat files inside a JAR
you would have to extract it and then run it
Please give more information on what it is you want the bat file to be doing and I can update this answer maybe there is another way?
Your problem can be divided into two parts: get the bat from the jarand run it.
To get the bat from the jar, you will have to use the ClassLoader to get a resource. you can achieve this by using the method Class.getResource to get the URL or Class.getResourceAsStream to get an InputStream
Anyway, i dont' think you can run the bat from inside the jar. If you try and fail, my advice is to create a temp file, copy your bat into your temp file and run that file.
P.S: Class.getResource finds file in the classpath. If your file is not in your classpath, you won't be able to find it this way.
EDIT: i add the code i'm using to get resources from a general relative path, given the path exist both starting from you working directory and from the home of your jar. It works, i've been able to just pack every folder i need into the jar and ship the jar to another compute rwhere eveything worked fine.
public static URL getResource(String name) {
if ("jar".equals(Main.class.getResource("Main.class").getProtocol())) {
return Main.class.getResource(("\\" + name).replace('\\', '/'));
} else {
try {
return (new File(System.getProperty("user.dir") + "\\" + name)).toURI().toURL();
} catch (MalformedURLException ex) {
return null;
}
}
}
Main is a known class, in this case the class where this static method is. I first use it to get a known url, and see if i am executing from a jar. If i am, i use the getResource, otherwise i use the File api.
the structure i use is this
main_folder\
res\
src\
package\
and, in the jar
file.jar\
package\
res\
and i need to use both File api and getResource since in the rist case the res folder is not in my classpath. with a different structure probably only the getResource method is fine.
This should solve your problem of getting the bat file, you still need to see if you are able to run it, and if you are not, copy everything into a temp file and run the temp file instead.
I'm tried several ways to zip a directory structure in a zip file with Java. Don't matter if I use ZipOutputStream or the Java NIO zip FileSystem, I just can't add empty folders to the zip file.
I tried with unix zip, and it works as expected, so I discarded a possibly zip-format issue.
I could also do a little workaround, adding an empty file inside the folders, but I don't really want to do that.
Is there a way to add empty folders in zip files using java API's?
EDIT: Based on answers and comments, this is pretty much the solution I got.
Thanks!
Java NIO makes this as easy as working with a normal file system.
public static void main(String[] args) throws Exception {
Path zipfile = Paths.get("C:\\Users\\me.user\\Downloads\\myfile.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(zipfile, null);) {
Path extFile = Paths.get("C:\\Users\\me.user\\Downloads\\countries.csv"); // from normal file system
Path directory = zipfs.getPath("/some/directory"); // from zip file system
Files.createDirectories(directory);
Files.copy(extFile, directory.resolve("zippedFile.csv"));
}
}
Given a myfile.zip file in the given directory, the newFileSystem call will detect the file type (.zip mostly gives it away in this case) and create a ZipFileSystem. Then you can just create paths (directories or files) in the zip file system and use the Java NIO Files api to create and copy files.
The above will create the directory structure /some/directory at the root of the zip file and that directory will contain the zipped file.
Are there any built-in methods I can use to allow users to extract a file from the currently running JAR and save it on their disk?
Thanks in advance.
File file = new File("newname.ext");
if (!file.exists()) {
InputStream link = (getClass().getResourceAsStream("/path/resources/filename.ext"));
Files.copy(link, file.getAbsoluteFile().toPath());
}
Use getResourceAsStream (docs), you can do whatever you want with it after that.
For a two-liner you could use one of the Commons IO copy methods.
I am not sure whether you will get know from which jar your class is getting executed but you can try this to extract resources from jar :
How to write a Java program which can extract a JAR file and store its data in specified directory (location)?
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"));