java.ioRandomAccessFile
-
RAF是专门用来读写文件数据的类,其基于指针对文件进行随机访问.读写操作灵活
RandomAccessFile常用构造器
RandomAccessFile(String path,String mode)
RandomAccessFile(File file,String mode)
第一个参数是要操作的文件,可以直接给路径,或指定一个File对象
第二个参数为操作模式:
r:只读
rw:读写模式
void write(int d)
向文件中写入1个字节,写入的是给定的int值对应的2进制的"低八为"
int read()
读取一个字节并以int形式返回(读取的数字在int值对应2进制低八位上)
如果返回int值为-1则表示文件末尾
long pos = raf.getFilePointer(); //获取RAF指针的位置
raf.writeInt(imax); //连续写4个字节将int值写入文件
raf.writeLong(123L); //连续写8个字节long值写入文件
System.out.println(“pos:”+raf.getFilePointer());
raf.writeDouble(123.123); //连续写8个字节double写入文件
单字节读取复制文件
RandomAccessFile src = new RandomAccessFile("SE.pptx","r");
RandomAccessFile desc = new RandomAccessFile("SE_CP.pptx","rw");
int d; //用于记录每次读取到的字节
while ((d=src.read()) != -1){
desc.write(d);
}
long end = System.currentTimeMillis();
System.out.println("复制完毕!耗时:"+end);
src.close();
desc.close();
块读写复制文件
RandomAccessFile src = new RandomAccessFile("abc.exe","r");
RandomAccessFile desc = new RandomAccessFile("abc_cp.exe","rw");
/*
int read(byte[] data)
一次性从文件中读取给定的字节数组总长度的字节量,并存入到数组中
返回值为实际读取到的字节量,如果返回为-1则表示末尾文件
void write(byte[] data)
一次性将给定的字节数组中的字节写入文件
*/
byte[] data = new byte[1024*10];
int len; //记录每次实际读取到的字节数
long start = System.currentTimeMillis();
while((len = src.read(data)) != -1){
//从原文件实际读取到多少个字节,就写多少个字节
desc.write(data,0,len);
}
long end = System.currentTimeMillis();
System.out.println("复制完毕!耗时:"+(end-start)+"ms");
src.close();
desc.close();
完成用户注册功能
- 程序启动后要求用户顺序输入:用户,密码,昵称,年龄
- 然后将该用信息写入到文件user.dat中保存.
- 设计格式:
- 每条记录固定占用100字节,其中用户名,密码,昵称各占32字节,年龄固定4字节
- 对于字符集而言故意留空白好处是后期再添加字符是可以的,不会影响其他数据.而且
- 长度固定利于指针的移动操作
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎注册");
System.out.println("请输入用户名");
String username = scanner.nextLine();
System.out.println("请输入密码");
String password = scanner.nextLine();
System.out.println("请输入昵称");
String nickname = scanner.nextLine();
System.out.println("请输入年龄");
int age = scanner.nextInt();
RandomAccessFile raf = new RandomAccessFile("user.dat","rw");
//先将指针移动到文件末尾
raf.seek(raf.length());
//写入用户名
byte[] data = username.getBytes("UTF-8");
//将数组扩容到32字节
data = Arrays.copyOf(data,32);
raf.write(data); //写入32字节
//写密码
data = password.getBytes("UTF-8");
data = Arrays.copyOf(data,32);
raf.write(data);
//写昵称
data = nickname.getBytes("UTF-8");
data = Arrays.copyOf(data,32);
raf.write(data);
raf.writeInt(age);
System.out.println("注册完毕");
raf.close();
读取注册的内容:
RandomAccessFile raf = new RandomAccessFile("user.dat","rw");
for(int i=0;i<raf.length()/100;i++){
byte[] data = new byte[32];
raf.read(data);
String username = new String(data,"UTF-8").trim();
raf.read(data);
String password = new String(data,"UTF-8").trim();
raf.read(data);
String nickname = new String(data,"UTF-8").trim();
int age = raf.readInt();
System.out.println(username+","+password+","+nickname+","+age);
}
raf.close();