[英]How to read from command line parameter or stdin redirection in java?
在這個 stackoverflow.com 響應中,我看到了如何同時獲得兩者,但不是分別獲得。
我想在 java 命令行中獲取參數或標准輸入重定向。
我以這種方式解決了它:
public static void main(String[] args) {
String fileInput = "";
try {
if (System.in.available() > 0) {
InputStreamReader isr = new InputStreamReader(System.in);
int ch;
while((ch = isr.read()) != -1) {
//System.out.print((char)ch);
fileInput += (char)ch;
}
}
} catch(IOException e) {
e.printStackTrace();
}
if ( ((fileInput.length() > 0) && (args.length > 0)) ||
((fileInput.length() == 0) && (args.length != 1)) ||
((fileInput.length() == 0) && (args.length == 0))
) {
System.out.println("Use: myprogram \"string\"");
System.out.println("Use: myprogram < file");
System.exit(0);
}
但我有一個疑問。 As Oracle 10 help says: "Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread或另一個線程。單次讀取或跳過這么多字節不會阻塞,但可能會讀取或跳過更少的字節
請注意,雖然 InputStream 的某些實現將返回 stream 中的總字節數,但許多不會。 使用這個方法的返回值來分配一個緩沖區來保存這個 stream 中的所有數據是不正確的。
我的問題是:方法 available() 總是會知道有一個標准重定向? 當有標准重定向時總是返回 > 0?
在我的測試中運行良好,但我不知道它是否在所有實現中都能正常運行。
如果您從另一個程序進行管道傳輸, otherprogram | myprogram
otherprogram | myprogram
,另一個程序提供數據的速度可能很慢,因此您無法對此進行測試。
出於這個原因,命令,特別是在 Linux 上,通常會指定參數值-
以指示應從 STDIN 讀取數據。
例如
# No-arg call prints options
myprogram
# Arg not '-' means to use argument value
myprogram "string"
# '-' means to read STDIN
myprogram - < file
otherprogram | myprogram -
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.