Java 对我来说是个新手。
我正在使用 Runtime.getRuntime.exec(filename.bat)
执行一个批处理文件,这个批处理文件执行一个命令ant encrypt.password -Dvalue=somevalue>log.txt
并将其输出重定向到 log.txt 文件。
我面临的问题是,如果我手动运行批处理文件,它可以正常工作,但是当程序执行它时,它只会创建空白的“log.txt”
mybat.bat
批处理文件内容如下:
cd/
c:
cd c:/ant_builds/thinclient
ant encrypt.password -Dvalue=someValue >C:/log.txt
Java代码如下:
Process p=Runtime.getRuntime.exec("C:\mybat.bat");
p.waitFor();
似乎在创建日志文件后,同时执行命令的控制权从进程中出来。
我在这里阅读了将近 50 个主题,但没有找到解决方案。请帮帮我。
最佳答案
使用ProcessBuilder创建您的进程并调用 redirectOutput(File)
将输出重定向并附加到文件。
试试这段代码:
public class Test {
ProcessBuilder builder;
Path log;
public Test() {
try
{
log = Paths.get("C:\\log.txt");
if (!Files.exists(log))
{
Files.createFile(log);
}
builder = new ProcessBuilder("ant", "encrypt.password", "-Dvalue=someValue");
builder.directory(Paths.get("C:\\ant_builds\\thinclient").toFile());
builder.redirectOutput(ProcessBuilder.Redirect.appendTo(log.toFile()));
builder.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
}
对于jdk 1.6以下,使用如下代码:
public class Test {
ProcessBuilder builder;
Path log;
Process process;
BufferedReader br;
PrintWriter pw;
Charset charset = Charset.forName("UTF-8");
public Test() {
try {
log = new File("C:\\log.txt");
if (!log.exists()) {
log.createNewFile();
}
builder = new ProcessBuilder("ant", "encrypt.password","-Dvalue=someValue");
builder.directory(new File("C:\\ant_builds\\thinclient"));
builder.redirectErrorStream(true);
process = builder.start();
br = new BufferedReader(new InputStreamReader(process.getInputStream(),charset));
pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(log, true), charset));
(new Thread() {
public void run() {
try {
while (process.isAlive()) {
String s = null;
while ((s = br.readLine()) != null) {
pw.print(s);
pw.flush();
}
}
br.close();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
}
我不确定 ProcessBuilder 参数的顺序和列表,因此请尝试使用它们以使您的代码正常工作。
关于Java:使用 exec() 方法在其他文本文件中重定向 .bat 文件的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27547874/