【发布时间】:2019-04-12 11:22:35
【问题描述】:
我有一个接受输入流并打印它的代码。当我使用BufferedReader 时,代码会在控制台中打印流,但是当我使用DataInputStream 时,会出现以下错误:
Exception in thread "main" java.io.UTFDataFormatException: malformed input around byte 6351
at java.io.DataInputStream.readUTF(DataInputStream.java:656)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at Test.main(Test.java:14)
代码如下:
public class Test {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("host", port);
DataInputStream in = null;
// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
in = new DataInputStream(socket.getInputStream());
while(true){
// System.out.println(bufferedReader.readLine());
System.out.println(in.readUTF());
}
}
}
当我将readLine() 与DataInputStream 一起使用时,intellij 表明它已被弃用。最后,我需要读取流并将其逐行传递给另一个方法,如下所示:
line = in.readUTF();
我得到同样的错误。我该如何纠正错误?
【问题讨论】:
-
您通过
readUTF()读取输入流中的数据,从而对其施加了一些约束。显然数据不是有效的 UTF-8。见docs.oracle.com/javase/7/docs/api/java/io/…If the first byte of a group matches the pattern 1111xxxx or the pattern 10xxxxxx, then a UTFDataFormatException is thrown. -
好的。知道了。
stream基本上是字节。我需要使用某种Reader如BufferedReader来读取数据。
标签: java datainputstream