java,为什么DataInputStream在whitespace时拆分String

时间:2017-04-02 07:00:54

标签: java sockets datainputstream

所以我尝试了解SocketDataInputStream

当我尝试尝试时,我意识到DataInputStream读取字符串是分开的,意思是这样的:

客户端:

dos = new DataOutputStream(socket.getOutputStream());

String msg = "okay test some String"

dos.writeUTF(msg);

服务器端:

dis = new DataInputStream(socket.getInputStream());

while(true){

    msg = dis.readUTF();

    Syso(msg);

}

结果:

okay

test

some

String

我想在一行中完整阅读msg。我该怎么办?

1 个答案:

答案 0 :(得分:1)

使用BufferedReader

dis = new BufferedReader(new InputStreamReader(socket.getInputs()))
while(true){
   msg = dis.readLine() 
   System.out.println(msg);
}

或者您可以将System.out.println替换为System.out.print,而dis = new DataInputStream(socket.getInputStream()); while(true){ msg = dis.readUTF(); System.out.print(msg+" "); } 不会在最后打印新的换行符

{{1}}