[英]Passing input arguments via here document to bash script which runs java class where that input is needed
例子:我有一堂課
public class MyClass0 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input 1st string");
String s1 = reader.readLine();
System.out.println("Input 2nd string");
String s2 = reader.readLine();
System.out.println("Input 3rd string");
String s3 = reader.readLine();
System.out.println("1st string is " + s1);
System.out.println("2nd string is " + s2);
System.out.println("3rd string is " + s3);
}
}
我從腳本中調用它,並通過此處文檔傳遞輸入
#!/bin/sh
export JAVA_HOME=$HOME/java/jdk1.7.0_21;
export PATH=$JAVA_HOME/bin:$PATH;
java MyClass0;
./myscript.sh <<'EOL'
123
456
789
EOL
它按預期工作:
1st string is 123
2nd string is 456
3rd string is 789
但是,如果這樣做:
public class MyClass0 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input 1st string");
String s1 = reader.readLine();
System.out.println("1st string is " + s1);
MyClass1.read();
}
}
public class MyClass1 {
public static void read() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s2 = reader.readLine();
String s3 = reader.readLine();
System.out.println("2nd string is " + s2);
System.out.println("3rd string is " + s3);
}
}
我懂了:
1st string is 123
2nd string is null
3rd string is null
有什么想法使它起作用嗎? 要接受其他兩個參數,我該怎么辦? 我不能改變課程。
這是因為您打開了2個緩沖讀取器來處理相同的輸入流。
在MyClass0.main中,創建一個並閱讀第一行。 在內部,BufferedRead已讀取了盡可能多的內容(此處為全文),返回了第一行,並准備好在沒有任何IO訪問的情況下返回以下各行。
您將在MyClass1.read中打開第二個BufferedReader。 不幸的是, System.in
已經位於文件末尾,任何讀取都將返回null
。
如何解決:恕我直言,更干凈的方法是將BufferedReader傳遞給MyClass1.read:
...
MyClass1.read(reader);
}
}
public class MyClass1 {
public static void read(Reader reader) throws IOException {
String s2 = reader.readLine();
String s3 = reader.readLine();
System.out.println("2nd string is " + s2);
System.out.println("3rd string is " + s3);
}
}
這里的問題是您正在使用BufferedReader
來緩沖要由應用程序讀取的數據,並且如果您想用第二個代碼來達到期望的結果,則需要在不緩沖的情況下讀取System.in
。 這是一種可以幫助您從System.in
讀取而無需緩沖任何內容的方法
public static String readLine(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int c;
for (c = inputStream.read(); c != '\n' && c != -1 ; c = inputStream.read()) {
byteArrayOutputStream.write(c);
}
if (c == -1 && byteArrayOutputStream.size() == 0) {
return null;
}
String line = byteArrayOutputStream.toString("UTF-8");
return line;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.