Reputation:
I have a java class that uses a bat file to execute commands. However I developed it in Eclipse IDE. It works fine in there. But as I export it in a jar file, it fails to find the bat file that was included.(gives me an IOException)
The file structure in eclipse is as follows :
Project1
---->src
------>com.myproj
-------->BatFileRead.java
----md.bat
----ul.bat
md.bat and ul.bat is same level as src directory. After jarring it src folder disappears.
Could someone help me with this. Thanks
Upvotes: 1
Views: 2970
Reputation: 1496
Well this can be very dangerous. Be sure to use gloves when dealing with the BAT. They bite and quite painfull. Also try getting jar that has a big enough opening, although the bats will fit almost through any hole.
Good luck, and don't try this at home. This is done by professionals.
Upvotes: 1
Reputation: 1503439
In order to execute the command, you'll have to extract the bat file afterwards. You can't run executables which are inside jar files. Basically you'll need to open the batch file entry in the jar file as an input stream, and copy the data to a FileOutputStream
on disk. You won't be able to execute it until it's a proper standalone file on the file system.
If you're already trying to extract it, chances are you're using getResource
or getResourceAsStream
slightly incorrectly. This is easy to do, because it depends whether you're calling ClassLoader.getResourceAsStream
or Class.getResourceAsStream
. The first only ever uses absolute paths (implicitly) and the second can use either absolute or relative paths. For example, in your case you'd want:
BatFileRead.class.getResourceAsStream("/md.bat")
or
BatFileRead.class.getClassLoader().getResourceAsStream("md.bat")
Have you checked that the bat files are definitely ending up in the jar file? Just list the contents with
jar tvf file.jar
to see what's in there.
Upvotes: 5
Reputation: 87401
Try copying file.jar
to file.zip
, and opening file.zip
(e.g. just double clicking, or using e.g. 7-Zip). Can you find your .bat
files inside? If the .bat
file isn't there, you have to add the .bat
file to your Eclipse project, and rebuild in Eclipse. If the .bat
file is there, but you still get an IOException
opening it from you .java
application, then please post the code snippet triggering the IOException
, and please give a full listing of file.zip
(get the listing by extracting file.zip
to C:\testdir
, and running dir /s C:\testdir
in the command line).
Please note that Jon Skeet is right that although it is possible to open any file in the .jar
file as an InputStream
using java.lang.Class.getResourceAsStream
and java.lang.ClassLoader.getResourceAsStream
(see tutorial or find them in the Java API docs), but in order to execute a .bat
file inside, you have to extract the .jar
file first.
Upvotes: 0