【Java基础】IO流(1) —— 简介
【Java基础】IO流(2) —— 字符流
【Java基础】IO流(3) —— 字节流
【Java基础】IO流(4) —— 转换流、打印流
【Java基础】IO流(5) —— 序列流、内存流
【Java基础】IO流(6) —— 随机访问文件流、数据流
随机访问文件流
RandomAccessFile
继承自Object,随机访问文件
内部既有字节输入流,也有字节输出流
内部定义了一个数组,可以通过指针操作数组,从而实现了随机
构造方法
RandomAccessFile(File file,String mode)
RandomAccessFile(String name,String mode)
mode
访问模式
参数:
r —— 读 rws ——
rw —— 可读、可写 rwd ——
方法
- write(byte[] b)
从指定的字节数组写入 b.length 个字节到该文件,从当前文件指针开始
write(byte[] b, int off, int len)
从指定的字节数组写入 len 个字节,从偏移量 off 开始到此文件
write(int b)
将指定字节写入此文件
writeInt(int b)
将 int 写入文件为4个字节 - int read()
从该文件读取一个字节的数据。
int read(byte[] b)
从该文件读取最多 b.length 字节的数据到字节数组。
int read(byte[] b, int off, int len)
从该文件读取最多 len 个字节的数据到字节数组。
int readInt()
从该文件读取一个带符号的32位整数 - Long getFilePointer()
返回此文件中的当前偏移量 - seek(int pos)
设置文件指针偏移(从文件开头测量,发生下一次读取或写入的指针位置)
public static void reads() throws IOException{
RandomAccessFile raf=new RandomAccessFile("tmp.txt","r");
byte[] arr=new byte[4];
int num=raf.read(arr);
int age=raf.readInt();
System.out.println(new String(arr,0,num)+","+age);
raf.seek(16);
num=raf.read(arr);
age=raf.readInt();
System.out.println(new String(arr,0,num)+","+age);
raf.close();
}
public static void writes() throws IOException{
RandomAccessFile raf=new RandomAccessFile("tmp.txt","rw");
raf.write("张三".getBytes());
raf.writeInt(78);
Long pos=raf.getFilePointer();
System.out.println(pos);
raf.seek(16);
raf.write("李四".getBytes());
raf.writeInt(34);
pos=raf.getFilePointer();
System.out.println(pos);
raf.close();
}
数据流
DataInputStream DataOutputStream
构造方法
DateOutputStream(Output Stream out)
DateInputStream(InputStream in)
方法
public static void reads() throws IOException{
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
double d = dis.readDouble();
boolean boo = dis.readBoolean();
int a = dis.readInt();
System.out.println(d+","+boo+","+a);
}
public static void writes()throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeDouble(66.66);
dos.writeBoolean(false);
dos.writeInt(99);
dos.close();
}