版本
JDK8(JDK1.8)
DataOutput接口源码重点
1.DataOutput接口定义了一系列方法用于将任何Java类型的数据转换为一系列字节,并将这些字节写入二进制流
2.char类型在Java中分为外码和内码两种,且char类型是变长的,具体取决于其编码方式,但是一个char代表一个字符,不确定是多少字节,接口中writeChar(int v)方法默认写入两个字节
- 内码:某种语言运行时(在运行内存中),其char和string在内存中的编码方式,内码(运行内存)中的char使用UTF16的方式编码,一个char占用两个字节,但是某些字符占4个字节
- 外码:除了内码,其他任何都是外码,使用UTF8的方式编码,一个char占用1~6个字节
- UTF16编码中,英文字符占两个字节,绝大多数汉字(尤其是常用汉字)占用两个字节,个别汉字(在后期加入unicode编码的汉字,一般是极少用到的生僻字)占用四个字节。
UTF8编码中,英文字符占用一个字节,绝大多数汉字占用三个字节,个别汉字占用四个字节。
3.DataOutput接口中方法
| 方法名 | 作用 |
|---|---|
| void write(int b) | 将整型b的八个低位写入输出流,忽略b的24个高位, 因为一次write(int b) 只写入一个字节 |
| void write(byte b[]) | 将数组b中的所有字节按序从b[0]开始全部写入输出流 |
| void write(byte b[], int off, int len) | 将数组b中字节按序从偏移量b[off]开始写入len个字节到输出流 |
| void writeBoolean(boolean v) | 将布尔值v写入此输出流 |
| void writeByte(int v) | 将整型v的八个低位写入输出流,忽略b的24个高位 |
| void writeShort(int v) | 将整型v低两个字节写入输出流以表示参数的值,先写入两个字节中较高位的一个字节 |
| void writeChar(int v) | 将由两个字节组成的char值写入输出流 |
| void writeInt(int v) | 将由四个字节组成的int值写入输出流,从高位字节开始写每次写入一个字节,写四次 |
| void writeLong(long v) | 将由八个字节组成的long值写入输出流,从高位字节开始写每次写入一个字节,写八次 |
| void writeFloat(float v) | 将由四个字节组成的浮点值写入输出流,和writeInt(int v)类似 |
| void writeDouble(double v) | 将由八个字节组成的双精度值写入输出流,和writeLong(long v) 类似 |
| void writeBytes(String s) | 将字符串写入输出流,字符串是char数组,这个方法会忽略char高8位,只写入其低8位,即每个char写入一次 |
| void writeChars(String s) | 将字符串s中的每个字符按每个字符两个字节的顺序写入输出流 |
| void writeUTF(String s) | 先将两个字节的长度信息写入输出流,再跟字符串s中每个字符的修改UTF-8表示形式,每个字符将被转换为一个由一个、两个或三个字节 |
DataOutput接口很多方法都与DataInput接口对应,DataOutput将数据从内存写入到输出流,DataInput从输入流将数据写到内存,如writeBoolean(boolean v)此方法写入的字节可由接口DataInput的readBoolean方法读取
DataInput 源码可以看我这篇文章 DataInput
DataOutput接口源码
package java.io;
public
interface DataOutput {
void write(int b) throws IOException;
void write(byte b[]) throws IOException;
void write(byte b[], int off, int len) throws IOException;
void writeBoolean(boolean v) throws IOException;
void writeByte(int v) throws IOException;
void writeShort(int v) throws IOException;
void writeChar(int v) throws IOException;
void writeInt(int v) throws IOException;
void writeLong(long v) throws IOException;
void writeFloat(float v) throws IOException;
void writeDouble(double v) throws IOException;
void writeBytes(String s) throws IOException;
void writeChars(String s) throws IOException;
void writeUTF(String s) throws IOException;
}



