java 程序调用 输出重定向
在命令行中可以这样做:C:\Users\li>cd/dd:\testd:\test>javaprog1>output.txt将输出结果保存到output.txt文件中,现...
在命令行中可以这样做:
C:\Users\li>cd /d d:\test
d:\test>java prog1 > output.txt
将输出结果保存到output.txt文件中,现在想在java代码中实现。
private static void Compile()
{
// String cmd = "cmd /c Start C:\\hello.exe";
String cmd = "java d:\\test\\prog1 > output.txt";
Runtime rt = Runtime.getRuntime();
try {
rt.exec(cmd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这样写的代码不能达成目的,该怎样修改? 展开
C:\Users\li>cd /d d:\test
d:\test>java prog1 > output.txt
将输出结果保存到output.txt文件中,现在想在java代码中实现。
private static void Compile()
{
// String cmd = "cmd /c Start C:\\hello.exe";
String cmd = "java d:\\test\\prog1 > output.txt";
Runtime rt = Runtime.getRuntime();
try {
rt.exec(cmd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这样写的代码不能达成目的,该怎样修改? 展开
2个回答
展开全部
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.SequenceInputStream;
public class Processing
{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec("cmd");
SequenceInputStream sis = new SequenceInputStream(process.getInputStream(), process.getErrorStream());
InputStreamReader isr = new InputStreamReader(sis, "GBK");
BufferedReader br = new BufferedReader(isr);
// next command
OutputStreamWriter osw = new OutputStreamWriter(process.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
bw.write("cd /d d:/test");
bw.newLine();
bw.write("javac prog1.java > javac.txt");
bw.newLine();
bw.write("java prog1 > java.txt");
bw.newLine();
bw.flush();
bw.close();
osw.close();
// read
String line = null;
while(null != (line = br.readLine()))
{
System.out.println(line);
}
process.destroy();
br.close();
isr.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询