[英]Type mismatch when using “while(line = reader.readLine() != null)”
[英]Using ProcessBuilder to execute Linux Command and getting NULL from reader.readLine() although line count is 102
嘗試從InputStream打印行時出現NULL。 行數的確返回一個值,並且我正在打開的文件確實包含相同數量的行。
reader.readLine()
返回NULL。
reader.lines().count()
確實返回文件中正確的行數...
因此,我相信:
process.getInputStream()
我正在嘗試使用Java運行linux命令,該命令將打開服務器上的文件並打印出來/將其記錄到我的日志文件中。
我已經嘗試使用ProcessBuiler和Runtime.getRuntime.exec()
。 兩者都產生相同的結果... reader.readLine()
上為NULL。
一些帖子建議使用process.getOutputStream
。 其中返回0行計數和空行。
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("sh", "-c", "cat chris.txt");
processBuilder.directory(new File("/opt/tmp/FOLDER_NAME"));
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
logger.info("######### {}", line);
}
我希望將文件內容打印在日志文件中。
我在reader.readLine()
對象上得到了NULL。
readLine()
返回值為null
表示您已到達流的末尾。 因此,您的過程不會產生任何輸出。
如果文件實際上有一些內容,最可能沒有輸出的原因是您的子流程失敗。 例如,因為找不到外殼程序,找不到文件,文件不可訪問,...
檢查process.waitFor()
的返回值。 如果這不是0,則說明存在問題。 您可能還想捕獲過程的stderr
,因為其中包含潛在的錯誤消息。 一種簡單的方法是使用ProcessBuilder.redirectErrorStream(true)
將錯誤流重定向到輸出流。
我發現了問題...似乎我在使用線路之前先進行了線路計數,從而耗盡了流。
對另一則帖子的評論幫助我找到了這個...
“ while和for的行為本質上是相同的;之所以從不“返回”,可能是由於您在countlines()方法中“耗盡”了流。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.