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;
}
}