[英]Java: Read InputStreamReader to String - Adding extra characters
[英]Why a new InputStreamReader won't read the remaining characters in the console?
所以我有一個用Java編寫的非常簡單的服務器:
public class SimpleServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server Socket created, waiting for client...");
Socket accept = serverSocket.accept();
InputStreamReader inputStreamReader = new InputStreamReader(accept.getInputStream());
int read;
System.out.println("Client connected, waiting for input");
while ((read = inputStreamReader.read()) != -1) {
System.out.print((char) read);
}
}
}
這是我用來連接它的代碼:
public class SimpleClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost",8888);
OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());
InputStreamReader inputStreamReader;
char[] chars = new char[5];
while (true) {
System.out.println("Say something: ");
inputStreamReader = new InputStreamReader(System.in);
inputStreamReader.read(chars);
int x = 0;
for (int i=0;i<5;i++) {
if(chars[i]!='\u0000') {
x++;
}
}
outputStream.write(chars,0,x);
outputStream.flush();
chars = new char[5];
}
}
}
現在,當我在客戶端的終端中鍵入以下內容時:
123456789
我將在服務器的終端中看到:
Server Socket created, waiting for client...
Client connected, waiting for input
12345
但是,當我如下更改客戶端時:
public class SimpleClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost",8888);
OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
char[] chars = new char[5];
while (true) {
System.out.println("Say something: ");
inputStreamReader.read(chars);
int x = 0;
for (int i=0;i<5;i++) {
if(chars[i]!='\u0000') {
x++;
}
}
outputStream.write(chars,0,x);
outputStream.flush();
chars = new char[5];
}
}
}
然后對於相同的輸入,我將看到:
Server Socket created, waiting for client...
Client connected, waiting for input
123456789
我的問題是, System.out是一個靜態變量,在這種情況下,該變量已經打開並已連接到終端。 創建新的InputStreamReader對象時,為什么終端中的信息會丟失? 相同的終端傳遞給對象,不是嗎?
創建新的InputStreamReader對象時,為什么終端中的信息會丟失?
當您在InputStreamReader
上調用read()
時,它可以(而且經常會)從流中讀取比您實際請求更多的數據,並將其余數據存儲在緩沖區中,以滿足以后的read
調用。 我懷疑整個文本行實際上已被第一個InputStreamReader
讀取,因此當您為同一流構造第二個 InputStreamReader
,就沒有讀取的余地,並且您必須鍵入更多文本才能獲取它無所不能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.