笔记(十):RandomAccessFile类(一):基础的读出与写入

本文深入探讨了Java中RandomAccessFile类的使用方法,包括如何创建对象、设置权限以及读写文件内容。通过实例演示了如何向文件写入内容及从文件中读取数据。

什么是RandomAccessFile类

java.ioRandomAccessFile类能对文件中的内容进行读写操作

为什么需要RandomAccessFile类

因为File类能对文件进行基本操作,但不能操作文件的内容,而RandomAccessFile类可以对文件的内容进行任意的读写

RandomAccessFile类的使用

基本认识

向文件中写入内容

package com.tedu.raf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * java.io.RandomAccessFile
 * 是专门读写文件数据的API,基于指针对文件进行随机读写操作
 * 读写文件非常灵活
 * @author Wildmess
 *
 */
public class rafDemo {
	public static void main(String[] args) throws IOException {
		/*
		 * RandAccessFile对象的创建
		 */
		File file = new File("./raf.txt");
		RandomAccessFile rat = new RandomAccessFile(file, "rw");
		/*
		 * RandomAccessFile对象的权限
		 * r:只读模式
		 * rw:读写模式
		 * 			如果要创建文件时,则使用的就必须时读写模式
		 * 			只读模式,会报错
		 * 
		 */
		//但使用RandomAccessFile创建文件有更好的方法
		RandomAccessFile raf2 = new RandomAccessFile("./raf2.txt","rw");
		
		/*
		 * 下面代码写入的内容时
		 * 00000001
		 * raf2.write(int d);
		 * 功能是向指定文件中写入给定int值的2进制的第八位数据
		 * 
		 */
		raf2.write(1);//将1写入文件raf2
		System.out.println("over");
		//注:一定要关闭
		raf2.close();
	}
}

向文件中读取内容

package com.tedu.raf;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 使用RAF读取一个字符的内容
 * @author Wildmess
 *
 */
public class rafDemo2 {
	public static void main(String[] args) throws IOException {
		RandomAccessFile raf = new RandomAccessFile("./raf2.txt","r");
		/*
		 * int read()
		 * 从文件中读取一个字节的数据
		 * 装载到int值的低八位数据上,并放回这个int值
		 * 读到没有任何内容的位置时,那么返回-1,表示文件读完了 
		 */
		int d = raf.read();
		System.out.println(d);
		//
		d=raf.read();
		System.out.println(d);
		raf.close();
	}
}
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值