簡體   English   中英

在新進程上啟動cmd.exe,然后在其上啟動用戶掃描儀

[英]Start cmd.exe on new Process then user Scanner on it

有沒有一種方法可以通過ProcessBuilder打開cmd.exe ,然后引用其流,以便可以調用NewProcessOutputStream.println()Scanner s = new Scanner(NewProcessInputStream)

我知道我可以發出諸如cmd /c dir類的命令並讀取輸入流,但是我想打開cmd進程,然后訪問其流,以便可以在任何時候打印到它。

我在想什么可能嗎? 還是應該通過該過程執行另一個程序?

編輯(更新):輸出不符合預期

import java.io.*;
import java.util.*;

public class Terminal {
    public static void main(String[] args) throws IOException {

        Process cmd = new ProcessBuilder("cmd").start();

        PrintWriter writer = new PrintWriter(cmd.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(cmd.getInputStream()));

        writer.println("Hello");
        writer.println("World!");
        writer.println("How are you?");
        writer.close();

        String line;

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

輸出:

C:\Users\Paul\Desktop\temp\CLI\src>java Terminal
Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\Paul\Desktop\temp\CLI\src>Hello

C:\Users\Paul\Desktop\temp\CLI\src>World!

C:\Users\Paul\Desktop\temp\CLI\src>How are you?

C:\Users\Paul\Desktop\temp\CLI\src>

C:\Users\Paul\Desktop\temp\CLI\src>

是的,你可以用獲得的過程輸入Process.getOutputStream()並使用其輸出Process.getInputStream()

這是一個例子:

public class ProcessTest {

    public static void main(String[] args) throws IOException {
        Process grep = new ProcessBuilder("grep", "foo").start();

        PrintWriter writer = new PrintWriter(grep.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(grep.getInputStream()));

        writer.println("this is the first line");
        writer.println("this is the foo line");
        writer.println("this is the last line");
        writer.println("nope, another foo");
        writer.close();

        // EDIT: fixed end of stream check
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        reader.close();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM