[英]Java, reading and writing to input and output stream of Autoit script
我正在嘗試寫入輸出流並讀取簡單的Autoit腳本的輸入流。 如果不使用newLine()字符,則會得到預期的輸出:自動發送一行,將一行發送給Java,然后重復執行。 如果我添加了newLine()字符,似乎每個周期都會有一條額外的行發送給autoit。 為什么會這樣呢?
自動:
Local $line
While (True)
$line = ConsoleRead()
ConsoleWrite( $line & "to java" & @LF )
Sleep(25)
WEnd
Java的:
p = Runtime.getRuntime().exec("Test");
in = new BufferedReader( new InputStreamReader(p.getInputStream()));
out = new BufferedWriter( new OutputStreamWriter(p.getOutputStream()));
int i=0;
out.write("(" + i++ + ") to autoit");
out.newLine();
out.flush();
while ((line = in.readLine()) != null) {
System.out.println(line);
out.write("(" + i + ") to autoit");
out.newLine();
out.flush();
if(i++ > 9)
p.destroy();
}
輸出:
(0) to autoit
to java
(1) to autoit
(2) to autoit
to java
(3) to autoit
(4) to autoit
(5) to autoit
to java
(6) to autoit
(7) to autoit
(8) to autoit
(9) to autoit
to java
我預期的輸出:
(0) to autoit
to java
(1) to autoit
to java
(2) to autoit
to java
(3) to autoit
to java
(4) to autoit
to java
(5) to autoit
to java
(6) to autoit
to java
(7) to autoit
to java
(8) to autoit
to java
(9) to autoit
to java
無論如何,我都不是專家,但請考慮以下更改:
ConsoleRead()
一個問題是它沒有阻塞,並且我相信不會識別新行。 換句話說,它的行為與Java的Scanner.nextLine()類似。 StringSplit(...)
函數以@CRLF作為分隔符來分割行,然后使用ConsoleWrite(...)
將結果數組中的每個String推送到標准輸出 StringInStr(...)
函數測試指示其退出的令牌。 例如:
EchoCaller2.java
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class EchoCaller2 {
private static final String AUTO_IT_ECHOER = "Echoer.exe"; // AutoIt program
private static Scanner scan = null;
private static PrintStream out = null;
public static void main(String[] args) throws IOException,
InterruptedException {
ProcessBuilder pb2 = new ProcessBuilder(AUTO_IT_ECHOER);
pb2.redirectErrorStream();
Process p = pb2.start();
scan = new Scanner(p.getInputStream());
out = new PrintStream(new BufferedOutputStream(p.getOutputStream()));
new Thread(new Runnable() {
public void run() {
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
scan.close();
}
}).start();
for (int i = 0; i < 10; i++) {
out.println("(" + i + ") to autoit ");
out.flush();
}
out.println("exit ");
out.flush();
out.close();
}
}
回聲3
Local $line
While (True)
$line &= ConsoleRead()
$strArray = StringSplit($line, @CRLF)
If $strArray[0] > 0 Then
For $r = 1 to $strArray[0]
If StringLen($strArray[$r]) > 0 Then
ConsoleWrite($strArray[$r] & "to java" & @CRLF)
EndIf
Next
EndIf
If StringInStr($line, "exit") Then
Exit
EndIf
$line = ""
Sleep(25)
WEnd
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.