Running a batch file that's inside of a jar file

偶尔善良 提交于 2019-12-12 00:50:38

问题


I'm attempting to call a batch file which is packaged inside of a jar file from the jar file itself. I'm not altogether sure this is possible, but I figured if anyone knew how it would be someone on here.

import java.io.IOException;
import java.net.URISyntaxException;
public class FileLocationFinder {

    public static void main(String[] args) throws IOException, URISyntaxException {
        String curdir = System.getProperty("user.dir");
        System.out.println("The User.dir = " + curdir);
        File newFile = new File (FileLocationFinder.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        String strNewFile = newFile.toString();
        System.out.println("The New Path = " + strNewFile);     
        String abPath = new File(".").getAbsolutePath();
        System.out.println("The absolutePath = " + abPath);
        String conPath = new File(".").getCanonicalPath();
        System.out.println("The Canonical Path = " + conPath);
        runDir(strNewFile);
    }
    public static void runDir(String dir){
        final int exitVal;
        final Process dirprocess;
        try {
            System.out.println("Running from curdir");
            dirprocess = Runtime.getRuntime().exec(dir + "\\" + "SomeBatch.bat");
            try {
                exitVal = dirprocess.waitFor();
                if(exitVal == 0){
                    System.out.println("Dir worked");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The contents of SomeBatch.bat is

echo I was called

This runs as I expect it to when I compile then run. But when I create the jar file I get a lot of errors.


回答1:


You have to tell Java where to look for your .bat file, the way you have it now it's just searching the working directory for "dir\Somebat.bat". To search through the jar file for the .bat you need to utilize the ClassLoader's getResource or getResourceAsStream methods. You may then have to copy the .bat to the filesystem [such as the user.home directory] and use Runtime.exec() launch it from there.



来源:https://stackoverflow.com/questions/16343338/running-a-batch-file-thats-inside-of-a-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!