一.DataInput 和DataOutput接口
DataOutput
接口定义了下面用于以二进制格式写数组,字符,boolean
值和字符串的方法:
public void writeBoolean(boolean v) throws IOException {}
public void writeByte(int v) throws IOException {}
public void writeShort(int v) throws IOException {}
public void writeChar(int v) throws IOException {}
public void writeInt(int v) throws IOException {}
public void writeLong(long v) throws IOException {}
public void writeFloat(float v) throws IOException {}
public void writeDouble(double v) throws IOException {}
public void writeBytes(String s) throws IOException {}
public void writeChars(String s) throws IOException {}
public void writeUTF(String s) throws IOException {}
- 例如,
writeInt
总是将一个整数写出为4字节的二进制数量值,而不管它有多少位,writeDouble
总是将一个double
值写出为8字节的二进制数量值。 writeUTF
方法使用修订版的8位Unicode转换格式写出字符串。这种方式与直接使用标准的UTF-8
编码方式不同。其中,Unicode码元序列首先用UTF-16表示,其结果之后使用UTF-8规则进行编码。修订后的编码方式大于0xFFFF的字符的处理有所不同,这是为了向后兼容在Unicode还没有超过16位时构建的虚拟机。DataInputStream
类实现了DataInput
接口,为了从文件中读入二进制数据,可以将DataInputStream
与某个字节源相结合,例如FileInputStream
:
try(DataInputStream din = new DataInputStream(
new BufferedInputStream(
new FileInputStream("C:\\Users\\whz\\Desktop\\百度盘会员.txt")));
DataOutputStream dos = new DataOutputStream(new FileOutputStream("text.txt"));
)
{
byte[] bytes = new byte[1000];
while (din.read() != -1){
din.read(bytes);
dos.write(bytes);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}