我想在 Bash shell 中將輸入傳遞給 java:
$: echo "text" | java myClass
這是我的Java代碼:
public class myClass {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("argument: " args[0]);
}
else {
System.out.println("[Error] No argument given");
System.exit(1);
}
System.exit(0);
}
}
結果是:
$: echo "text" | java myClass
[Error] No argument given
uj5u.com熱心網友回復:
這更像是一個 shell 編程問題。
你需要寫:
$: java myClass $(echo "text")
這會將 echo 的輸出轉換為引數。當您的程式的輸出很簡單(例如,一個簡短的單詞串列)時,這將起作用。
如果您希望閱讀文本行,則必須使用原始命令并從標準輸入讀取輸入。
uj5u.com熱心網友回復:
如果您希望它像我們所做的cat <file> | cut -d...那樣作業,那么它不會在這里發生。當您將一個命令的輸出通過管道傳輸到另一個命令時,另一個命令必須從 stdin 讀取。
因此,您的 Java 程式應該從 stdin 讀取。
這是一個例子。
public class myClass{
public static void main( String[] args ){
String input = readIn();
System.out.println( input );
}
private static String readIn(){
try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[ 1024 ];
int bytesRead = -1;
while( ( bytesRead = System.in.read( buffer ) ) > 0 ){
baos.write( buffer, 0, bytesRead );
}
return baos.toString( StandardCharsets.UTF_8 );
}
catch( IOException e ){
throw new RuntimeException( e );
}
}
}
現在,在你編譯之后,你可以呼叫:
$ echo "text" | java myClass
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369243.html
