【Java基础】IO流(6) —— 随机访问文件流、数据流

【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();
}
  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值