DataOutputStream 详细介绍
1、DataOutputStreams 核心底层
DataOutputStreams是数据输出流,实现八种基本类型数据的输出。虽然DataOutputStreams的用法看似复杂,实则简单,它只要一个核心功能,如下所示:
public final void writeByte(int v) throws IOException {
out.write(v);
}
所有数据类型的输出都转换为字节数组,然后调用上面的核心函数进行数据输出。例如下面的int和long的输出:
public final void writeShort(int v) throws IOException {
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
}
public final void writeInt(int v) throws IOException {
out.write((v >>> 24) & 0xFF);
out.write((v >>> 16) & 0xFF);
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
}
private byte writeBuffer[] = new byte[8];
public final void writeLong(long v) throws IOException {
writeBuffer[0] = (byte)(v >>> 56);
writeBuffer[1] = (byte)(v >>> 48);
writeBuffer[2] = (byte)(v >>> 40);
writeBuffer[3] = (byte)(v >>> 32);
writeBuffer[4] = (byte)(v >>> 24);
writeBuffer[5] = (byte)(v >>> 16);
writeBuffer[6] = (byte)(v >>> 8);
writeBuffer[7] = (byte)(v >>> 0);
out.write(writeBuffer, 0, 8);
}
2、逻辑类型数据的输出
逻辑数值的输出是通过1和0来表示的:
public final void writeBoolean(boolean v) throws IOException {
out.write(v ? 1 : 0);
}
3、字符类型数据的输出
字符类型数据分为两种情况:单字节编码的字符串和多字节编码的字符串(UTF字符串)。
public final void writeBytes(String s) throws IOException {
int len = s.length();
for (int i = 0 ; i < len ; i++) {
out.write((byte)s.charAt(i));
}
}
public final void writeUTF(String str) throws IOException {
...
}
4、应用举例
public class Test
{
public static void main(String[] args)
{
try
{
File file = new File("E:\\out.txt");
FileOutputStream out = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(100);
dos.writeBytes("Hello world!");
dos.writeUTF("世界,你好!");
}
catch (FileNotFoundException e)
{
System.out.println("文件不存在");
}
catch (IOException e)
{
System.out.println("写入过程存在异常");
}
}
}