ไม่มีใครรู้วิธีใช้ linux grep กับ java ProcessBuilder หรือไม่ เหตุใดโค้ดนี้จึงส่งคืนสตริงว่างเมื่อควรส่งคืน "sing"
import java.io.*;
import java.util.*;
public class Test2 {
public static void main(String[] args) throws InterruptedException,IOException{
String line;
// Initiate grep process.
ProcessBuilder pb = new ProcessBuilder("grep", "\"sing\"", "<<<\"sing\"");
Process p = pb.start();
p.waitFor();
// Get grep output:
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.println(result);
}
}
ฉันยังพยายามสะท้อนสิ่งที่ฉันดำเนินการด้วยรหัสนี้:
ProcessBuilder pb = new ProcessBuilder("echo","grep", "\"sing\"", "<<<\"sing\"");
และรับผลลัพธ์ที่ถูกต้อง:
grep "sing" <<<"sing"
ในที่สุดฉันก็พยายามรันคำสั่งที่เชลล์และได้รับ:
sing
แม้ว่าจะเป็นตัวอักษรสีแดงด้วยเหตุผลบางประการก็ตาม แล้วฉันทำอะไรผิดล่ะ?
<<<
บอกให้เชลล์ส่งสิ่งใดก็ตามที่ตามมาเป็นสตรีมอินพุตไปยัง grep โค้ด ProcessBuilder ของคุณถือว่าสัญลักษณ์สตรีมอินพุตเป็นอาร์กิวเมนต์อื่น - person Brian   schedule 31.01.2015