Java:与 DataInputStream 中的 dis.read() 和 dis.readUTF() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10891494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:00:04  来源:igfitidea点击:

Java: Difference with dis.read() and dis.readUTF() in DataInputStream

javasocketsserversocketdatainputstream

提问by reinhard.lee

Simple Question.

简单的问题。

What is Difference with dis.read()and dis.readUTF()?

什么是区别与dis.read()dis.readUTF()

For example, dis.read()only read to byte array, and dis.readUTF()access Stringtype.

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

Is it correct?

这是正确的吗?

If Server has implements dis.readUTF(), it can not read byte stream?

如果服务器有实现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;
            }

采纳答案by Muhammad Imran Saeed

readUTF() reads from the stream in a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String.

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

You should use read method which takes bytes array as an argument. Here is its explanation:

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

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

public final int read(byte[] b) 抛出 IOException

Reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.

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