2012-08-31 62 views
1

我想從Unix(bash)命令行向以下Java程序發送文本輸入,以便打印輸入的文本。我如何編寫一個shell腳本將字符串「Print this」發送到Java程序?使用shell腳本寫入程序的標準輸入

import java.util.Scanner; 
public class ReadStuff{ 
    public static void main(String[] args){ 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Enter some text:"); 
     System.out.println(scan.nextLine()); 
    } 
} 
+0

如果你的程序只在命令行中輸入的需要,那麼你就可以按照這種方式:http://docs.oracle.com/javase /tutorial/essential/environment/cmdLineArgs.html –

+0

我需要修改程序(因爲它目前存在於此頁面上)才能使其運行? –

+0

是的,你必須。 –

回答

6

使用echo

echo "Print this" | java ReadStuff 

注意,這將輸出:

Enter some text: 
Print 

因爲你調用Scanner.next()讀取下一個單詞,而不是整個行。

或者,如果你有東西在文件中:

cat file_with_Print_this | java ReadStuff 
+0

我打算寫'Scanner.nextLine()'。 –

+0

現在我應該怎麼做,如果我想要兩個程序來讀取彼此的輸入? –

+2

@AndersonGreen然後使用http://bisqwit.iki.fi/source/twinpipe.html –