[英]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.