简体   繁体   中英

execute a command using java and save generated output in another directory

I am working on an eclipse rcp product where I need to run a command from one directory and need to save the output in another directory.

The output of a command is a file.

I am not getting how to do that.

My code is like this which is not working.

Runtime r = Runtime.getRuntime();
Process  p = r.exec(("CMD /C cd D:\\dir1\\bin" + " && " + command),
            null, new File("D:\\Data\\test"));

so, command needs to run from dir1/bin and the output of this command is a file which should save in data/test.

But from the above code, the output(ie. generated file) is saved in dir1/bin which is not expected.

echo This is a command > output.txt

尝试在命令末尾添加“ > output.txt ”,以将其插入文件

You can use the InputStream given by the process object (p.getInputStream()) and a FileOutputStream to a file. Create a new Thread with an endless while-loop, read the characters within that and write them to the file.

Process p = ....
InputStream is = p.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
new Thread(new Runnable() {
    public void run() {
        while (true) {
            char c = (char)is.read();
            if (c > -1) {
                fos.write(c);
            } else {
                return;
            }
        }
    }
}).start();

I did not test the code but it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM