RandomAccessFile学习

package com.imooc;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class randomAccessFile {
	/**
	 * 在当前文件创建一个文件,并写入数据
	 * 需要回避异常
	 */
	public static void main(String[] args) throws IOException {
		File test1 = new File("test1");
		if(!test1.exists())
			test1.mkdir();
		else
			System.out.println("文件目录存在");
		
		File text1 = new File(test1, "test1.dat");
		if(!text1.exists()) 
			text1.createNewFile();
		else
		 	System.out.println("文件存在");
		
		RandomAccessFile raf = new RandomAccessFile(text1, "rw");
		//输出指针位置
		System.out.println("创建RandomAccessFile对象后指针位置: " + raf.getFilePointer());
		//输出0
		raf.write('A');
		//char类型占1个字节
		System.out.println("输入一个字节后指针的位置: " + raf.getFilePointer());
		//输出1
		raf.writeBytes("BCD");
		//String类型占3个字节
		System.out.println("输入一个字符串后指针的位置: " + raf.getFilePointer());
		//输出4
		int maxint = 0x7fffffff;
		//用write方法每次只能写入1个字节,因此写入最大类型的int型需要写入四次
		raf.write(maxint >>> 24);
		raf.write(maxint >>> 16);
		raf.write(maxint >>> 8);
		raf.write(maxint);
		System.out.println("输入最大整型之后指针位置: " + raf.getFilePointer());
		//输出8
		raf.writeInt(maxint);
		System.out.println("输入最大整型之后指针位置: " + raf.getFilePointer());
		//输出12
		String s = "中";
		byte[] str = s.getBytes();
		raf.write(str);
		//一个汉字占两个字节
		System.out.println("输入中文字节数组之后指针位置: " + raf.getFilePointer());
		//输出14
		String ss = "中国人";
		byte[] str1 = ss.getBytes("gbk");
		raf.write(str1);
		System.out.println(raf.getFilePointer());
		//读取文件需要先将指针归零
		raf.seek(0);
		//一次性读取, 把文件内容读到字节数组中
		byte[] buf = new byte[(int)raf.length()];
		raf.read(buf);
		System.out.println(Arrays.toString(buf));
		String s1 = new String(buf);
		System.out.println(s1);
		
		for (byte b : buf) {
			System.out.println(Integer.toHexString(b & 0xff) + ", ");
		}
		//关闭
		raf.close();
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值