【问题标题】:Malformed input around byte in Java while using DataInputStream使用 DataInputStream 时 Java 中字节周围的输入格式错误
【发布时间】: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 基本上是字节。我需要使用某种ReaderBufferedReader 来读取数据。

标签: java datainputstream


【解决方案1】:

可能有点晚了,但这里有一个答案。 在下面的代码中你不应该写:

Socket socket = new Socket("host", port);

Socket 需要一个 IP 地址而不是名称。 例如应该是:

Socket socket = new Socket("192.168.0.87", port);

【讨论】:

  • 这根本不是他所质疑的。
  • 我假设提出问题的人修改了他们使用的 IP
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
相关资源
最近更新 更多