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();
}
}
RandomAccessFile学习
最新推荐文章于 2020-09-08 11:53:37 发布