![](/img/trans.png)
[英]Different outputs each time this synchronized multithread program is run(Java.)
[英]Java: Getting different output each time I run the program for the same input
環境:運行程序時使用的輸入文件重定向,IDE:Eclipse。
我正在從 System.in 讀取數據包(因為使用了輸入重定向),並計算數據包的數量。 每次我為相同的輸入運行程序時,我都會得到不同的計數(都是錯誤的)。 另外,當我在控制台上顯示很多東西時,我得到了正確的計數。
int packetNumber = 0;
while(System.in.available()>0)
{
System.out.println("\n" + packetNumber + ": ");
int numberOfBytes = System.in.read();
byte[] buffer = new byte[numberOfBytes];
System.in.read(buffer, 0, numberOfBytes);
packetNumber++;
}
System.out.println("Number of packets = " + packetNumber);
使用 System.out.println() 工作正常,但沒有它會表現得很奇怪
提前致謝。
read(byte[] b, int off, int len)
不需要填充緩沖區:
從輸入流中讀取最多
len
個字節的數據到一個字節數組中。 嘗試讀取多達len
個字節,但可能會讀取較小的數字。 實際讀取的字節數作為整數返回。
那是因為緩沖,以及發送數據的程序和接收數據的程序的性能差異,這會影響下次調用read()
緩沖區中累積的字節數。
假設每次調用read()
返回一個“數據包”肯定是錯誤的。
如果將返回值捕獲為bytesRead
並將它們相加,則應始終獲得相同的總數。
byte[] buffer = new byte[numberOfBytes];
int totalBytes = 0;
int bytesRead;
while ((bytesRead = System.in.read(buffer)) != -1) {
totalBytes += bytesRead;
}
System.out.println("Received " + totalBytes + " bytes");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.