java RandomAccessFile类文件基本操作

RandomAccessFile类是java中仿C的文件操作方法,下面通过实例演示RandomAccessFile类对文件的基本操作,深入了解请查看Java API文档。(注:RandomAccessFile类大多不被采用)

上代码

import java.io.*;

public class AccessFileDemo
{
	public static void main(String[] args)
	{
		Student stu1=new Student("Zhang San",10);
		Student stu2=new Student("Li Si",11);
		Student stu3=new Student("Wang Wu",12);
		
		try 
		{
			//未找到文件时自动创建新文件
			RandomAccessFile af=new RandomAccessFile("F:\\workspace\\JavaPrj\\test.txt","rw");
			af.writeBytes(stu1.name);
			af.writeInt(stu1.age);
			af.writeBytes(stu2.name);
			af.writeInt(stu2.age);
			af.writeBytes(stu3.name);
			af.writeInt(stu3.age);
			af.close();
			
			af=new RandomAccessFile("F:\\workspace\\JavaPrj\\test.txt","r");
			System.out.println("The second person's information is");
			int len=8;
			String str=new String();
			af.skipBytes(12);
			while(len>0)
			{
				str=str+(char)af.readByte();
				len--;
			}
			System.out.println("Name: "+str);
			System.out.println("Age : "+af.readInt());
			
			System.out.println("The first person's information is");
			af.seek(0);
			len=8;
			str="";
			while(len>0)
			{
				str=str+(char)af.readByte();
				len--;
			}
			System.out.println("Name: "+str);
			System.out.println("Age : "+af.readInt());
			
			System.out.println("The third person's information is");
			af.skipBytes(12);
			len=8;
			str="";
			while(len>0)
			{
				str=str+(char)af.readByte();
				len--;
			}
			System.out.println("Name: "+str);
			System.out.println("Age : "+af.readInt());
		} 
		catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class Student
{
	String name;
	int age;
	
	Student(String str,int num)
	{
		if(str.length()>8)
		{
			str=str.substring(0, 8);	//从索引0到索引7的字符
		}
		else
		{
			while(str.length()<8)
			{
				str=str+"\u0000";
			}
		}
		name=str;
		age=num;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值