【问题标题】:Java: Difference with dis.read() and dis.readUTF() in DataInputStreamJava:与 DataInputStream 中的 dis.read() 和 dis.readUTF() 的区别
【发布时间】:2012-06-09 03:03:47
【问题描述】:

简单的问题。

dis.read()dis.readUTF() 有什么区别?

例如dis.read()只读取字节数组,而dis.readUTF()访问String类型。

对吗?

如果Server有实现dis.readUTF(),它不能读取字节流?

@Override
public void run() {
    // TODO Auto-generated method stub
    while(mEnabled)
    {
        if (!mFileReceive) {
            try {
                // read
                String tmpStr = dis.readUTF();
                // here come `dis.readUTF()` <- it is can not read byte array?

                mStringBuffer += tmpStr;

                if (tmpStr.length() >= 4096)
                    continue;
                System.out.println("Print : " + mStringBuffer);

                parse = new ParseJSON(null, mStringBuffer.toString());
                // Ack Message
                if (mAckEnabled) {
                    mFileName = "{opcode:0x06,ACK:C" + parse.getParsedData().get("ACK").substring(1) + "}";
                    dos.writeUTF(mFileName);
                    dos.flush();
                    System.out.println("Ack Message Send : " + mFileName);
                    mFileName = null;
                }
                if (parse.getParsedData().get("opcode").equals("155")) {
                    mFileReceive = true;
                }
                parse.clear();
                parse = null;

            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("ServerThread disconnect");
                break;
            }

【问题讨论】:

  • (1) Javadoc 的哪一部分您不理解? (2) “如果Server有实现dis.readUTF(),它不能读取字节流?”是没有意义的。 DataInputStreamObjectInputStream 实现了这两种方法。
  • @EJP 我的问题是 'dis.readUTF' 可以读取字节流。 JAVADOC 说 从包含的输入流中读取此操作的字节。 客户端发送到服务器字节数组。但是服务器没有抓住它。
  • 所有那些从字节流中读取的 API。但是readUTF() 读取的格式是writeUTF() writes. If you're not calling writeUTF()` 我不明白你为什么要调用readUTF()
  • @EJP 非常感谢,readUTF()writeUTF() 看起来像合作伙伴。
  • @EJP 我的 Ubuntu 使用 Locale KO_KR.utf8。所以,我打算使用'readUTF()'。太感谢了。您的建议很有帮助。

标签: java sockets serversocket datainputstream


【解决方案1】:

readUTF() 从流中读取以修改的 UTF-8 格式编码的 Unicode 字符串的表示形式;然后这个字符串作为字符串返回。

您应该使用以字节数组作为参数的读取方法。这是它的解释:

public final int read(byte[] b) throws IOException

从包含的输入流中读取一些字节并将它们存储到缓冲区数组 b 中。实际读取的字节数以整数形式返回。

【讨论】:

  • @11684 没错,那是我的古玩。
  • @EJP 客户端发送到服务器字节数组数据。
  • @reinhard.lee 在这种情况下,您应该在问题中提到这一点。你没有说客户在写什么。
  • @EJP 对不起。我不知道。
猜你喜欢
  • 2012-04-06
  • 2012-02-13
  • 2012-06-18
  • 1970-01-01
  • 2011-10-04
  • 1970-01-01
  • 2018-03-23
  • 2018-03-09
  • 2021-05-16
相关资源
最近更新 更多