基本数据类型流: 读入写出基本数据类型+字符串类型的数据,是字节流的一个功能流
一、输入流DataInputStream
数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。
构造方法
DataInputStream(InputStream in)
使用指定的底层 InputStream 创建一个 DataInputStream。
DataInputStream is=new DataInputStream(new BufferedInputStream(new FileInputStream("D:/test.txt")));
方法:
int read(byte[] b)
从包含的输入流中读取一定数量的字节,并将它们存储到缓冲区数组 b 中。int read(byte[] b, int off, int len)
从包含的输入流中将最多 len 个字节读入一个 byte 数组中。boolean readBoolean()
参见 DataInput 的 readBoolean 方法的常规协定。byte readByte()
参见 DataInput 的 readByte 方法的常规协定。char readChar()
参见 DataInput 的 readChar 方法的常规协定。double readDouble()
参见 DataInput 的 readDouble 方法的常规协定。float readFloat()
参见 DataInput 的 readFloat 方法的常规协定。void readFully(byte[] b)
参见 DataInput 的 readFully 方法的常规协定。void readFully(byte[] b, int off, int len)
参见 DataInput 的 readFully 方法的常规协定。int readInt()
参见 DataInput 的 readInt 方法的常规协定。long readLong()
参见 DataInput 的 readLong 方法的常规协定。short readShort()
参见 DataInput 的 readShort 方法的常规协定。int readUnsignedByte()
参见 DataInput 的 readUnsignedByte 方法的常规协定。int readUnsignedShort()
参见 DataInput 的 readUnsignedShort 方法的常规协定。String readUTF()
参见 DataInput 的 readUTF 方法的常规协定。static String readUTF(DataInput in)
从流 in 中读取用 UTF-8 修改版格式编码的 Unicode 字符格式的字符串;然后以 String 形式返回此字符串。
步骤
- 选择流
- 读入
- 关闭
实例
public static void read(String path) throws IOException{
//1.选择流
DataInputStream is=new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
//2.读入 写出与读入的顺序要相同
int i=is.readInt();
String s=is.readUTF();
System.out.println(i+"-->"+s+);
//3.关闭
is.close();
}
三、输出流DataOutputStream
数据输出流允许应用程序以适当方式将基本 Java 数据类型写入输出流中。
构造方法
DataOutputStream(OutputStream out)
创建一个新的数据输出流,将数据写入指定基础输出流。
Writer write=new FileWriter("D:/test.txt",true);
方法:
void flush()
清空此数据输出流。int size()
返回计数器 written 的当前值,即到目前为止写入此数据输出流的字节数。void write(byte[] b, int off, int len)
将指定 byte 数组中从偏移量 off 开始的 len 个字节写入基础输出流。void write(int b)
将指定字节(参数 b 的八个低位)写入基础输出流。void writeBoolean(boolean v)
将一个 boolean 值以 1-byte 值形式写入基础输出流。void writeByte(int v)
将一个 byte 值以 1-byte 值形式写出到基础输出流中。void writeBytes(String s)
将字符串按字节顺序写出到基础输出流中。void writeChar(int v)
将一个 char 值以 2-byte 值形式写入基础输出流中,先写入高字节。void writeChars(String s)
将字符串按字符顺序写入基础输出流。void writeDouble(double v)
使用 Double 类中的 doubleToLongBits 方法将 double 参数转换为一个 long 值,然后将该 long 值以 8-byte 值形式写入基础输出流中,先写入高字节。void writeFloat(float v)
使用 Float 类中的 floatToIntBits 方法将 float 参数转换为一个 int 值,然后将该 int 值以 4-byte 值形式写入基础输出流中,先写入高字节。void writeInt(int v)
将一个 int 值以 4-byte 值形式写入基础输出流中,先写入高字节。void writeLong(long v)
将一个 long 值以 8-byte 值形式写入基础输出流中,先写入高字节。void writeShort(int v)
将一个 short 值以 2-byte 值形式写入基础输出流中,先写入高字节。void writeUTF(String str)
以与机器无关方式使用 UTF-8 修改版编码将一个字符串写入基础输出流。
步骤
- 选择输出流
- 写出
- 刷出
- 关闭
实例
public static void write(String path) throws IOException{
//1.选择输出流
DataOutputStream os=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
//2.写出
int i=101;
String s="哈哈";
boolean b=false;
os.writeInt(i);
os.writeUTF(s);
os.writeBoolean(b);
//3.刷出
os.flush();
//4.关闭
os.close();
}