filena-6ren">
gpt4 book ai didi

java - 运行时问题

转载 作者:行者123 更新时间:2023-12-03 20:24:22 27 4
gpt4 key购买 nike

如何在 Windows 上运行,文件 filename.txt 没有被创建。

Process p = Runtime.getRuntime().exec("cmd echo name > filename.txt");

显然预期的输出是一个“filename.txt”应该被创建(C:\Documents and Settings\username\filename.txt),内容为“name”。


能够使用以下代码进行管理,即使文件“filename.txt”不是使用 processBuilder 创建的

       Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c cleartool lsview");
// Directly to file

//Process p = Runtime.getRuntime().exec(
// new String[] { "cmd", "/c", "cleartool lsview > filename.txt" },null, new File("C:/Documents and Settings/username/"));

InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:",
Arrays.toString(args));

while ((line = br.readLine()) != null) {
System.out.println(line);
}

或者,使用 ProceessBuilder,

Process process = new ProcessBuilder( "cmd", "/c", "cleartool lsview" ).start();
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));

System.out.printf("Output of running %s is:", Arrays.toString(args));

String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}

最佳答案

你实际上应该使用 ProcessBuilder而不是 Runtime.exec(参见 the docs)。

ProcessBuilder pb = new ProcessBuilder("your_command", "arg1", "arg2");
pb.directory(new File("C:/Documents and Settings/username/"));

OutputStream out = new FileOutputStream("filename.txt");
InputStream in = pb.start().getInputStream();

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);

out.close();

(如果我有一台 windows 机器,我会使其适应 cmd 和 echo ......随时编辑这篇文章!)

关于java - 运行时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3777654/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com