简体   繁体   中英

redirecting output of command prompt to a text file using java in windows

I am launching command prompt using java by following code

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd /c start cmd.exe /K \"dir > D:\test1.txt");

after executing second line I am getting error as 'Access is denied' and I can't redirect output of command prompt to a text file.

Can somebody please help?

Double the backslash after D: , so that it's not inserting a tab ( \\t ) in the command string:

Process proc = rt.exec("cmd /c start cmd.exe /K \"dir > D:\\test1.txt");

You will also need to fix that quote ( \\" ) you inserted, because it's not ended. Either remove it, or add an appropriate end-quote (at the end?).

You can use

Process proc = rt.exec("cmd /c start cmd.exe /K \"dir);

 OutputStream = proc.getOutputStream();

And then write the output to the file

Backslashes are used before escape characters in java. You need to format the path properly

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