我有一個執行PowerShell腳本的Java應用程序。
在我的java代碼中,我從輸入流(來自腳本的數據)中讀取數據並寫入輸出流(數據發送到腳本)。我也分別處理錯誤流。
在PowerShell腳本我使用以下命令從腳本的標準輸入流中讀取:
PowerShell腳本卡住了ReadLine()
$Line = [Console]::ReadLine()
當該腳本到達代碼這一點上,掛在的ReadLine(),直到東西寫到流中,這是java應用程序的來源。
在java中,我將以下內容寫入輸出流(此代碼不是整個代碼,但一般而且只是其中的重要部分):
public void runMain()
{
String[] params = "the command and arguments here";
Process process = r.exec(params, null);
outStream = new BufferedOutputStream(process.getOutputStream());
inStream = new BufferedInputStream(process.getInputStream());
errStream = new BufferedInputStream(process.getErrorStream());
startCmd = "some text here\r\n";
wtByte = startCmd.getBytes();
outStream.write(wtByte, 0, wtByte.length);
outStream.flush();
while (!isScriptTerminated && !wasError && !isScriptFinished)
{
if (errStream != null)
{
// handle error
}
if (inStream != null)
{
// read the data from the STDOUT of the script (our input)
readBuffer = receive();
...
}
...
}
}
你有沒有可以看到我在開始時寫入outStream,然後調用flush()實際上將所有流都刷新到流中,但此時腳本被卡住並掛在ReadLine()上,並且我的java代碼到達receive()方法並等待腳本響應並寫入標準輸入內容,但在這種情況下,java代碼將永久掛起,因爲腳本永遠停留在ReadLine()上。然後過了一段時間,我有超時機制殺死進程並釋放程序。
在我做的實驗中,我在開始時重複了對outStream的寫作,它有時可以工作,有時不會。意思是,第二次沖洗寫到流和腳本得到它。
我必須說我使用相同的代碼來運行Perl,VB和Python腳本沒有任何問題。此外,此代碼在我的機器(Windows 10)上工作,而不是在Windows 7,Windows Server 2008等其他機器上工作。也許它與PowerShell版本有關?
問題是怎麼回事?
我能做些什麼來克服這個問題?
我沒有成功地在PowerShell中使用Read-Host命令,並且我得到了相同的行爲,是否有另一種方法來讀取PowerShell腳本?