运行一个批处理文件,这是一个jar文件内 [英] Running a batch file that's inside of a jar file

查看:128
本文介绍了运行一个批处理文件,这是一个jar文件内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打电话给被包装从jar文件本身一个jar文件里的批处理文件。我并不完全相信这是可能的,但我想如果有人知道怎么会有人在这里。

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();
        }
    }
}

SomeBatch.bat的内容是

The contents of SomeBatch.bat is

echo I was called

本运行,我期望它当我编译然后运行。但是,当我创建的jar文件我得到了很多的错误。

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.

推荐答案

您必须告诉的Java在哪里寻找你的.bat文件,你有它的方式,现在它只是搜索DIR \\ Somebat.bat工作目录。要通过你需要利用的ClassLoader的的getResource或的getResourceAsStream方法.BAT jar文件搜索。然后,您可能不得不将.bat复制到文件系统[如的user.home目录],使用的Runtime.exec()从那里启动它。

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.

这篇关于运行一个批处理文件,这是一个jar文件内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆