File类只是针对文件本身进行操作,而如果要对文件内容进行操作,则可以使用RandomAccessFile类,此类属于随机读取类,可以随机地读取一个文件中指定位置的数据。
//=================================================
// File Name : RandomAccessFile_demo
//------------------------------------------------------------------------------
// Author : Common
import java.io.File;
import java.io.RandomAccessFile;
//主类
//Function : RandomAccessFile_demo
public class RandomAccessFile_demo {
public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根
File f = new File("/home/common/software/coding/HelloWord/HelloWord/test.txt");//路径
RandomAccessFile rdf = null; //声明一个RandomAccessFile类对象
rdf = new RandomAccessFile(f,"r"); //以读写方式打开文件,会自动创建新文件
String name = "zhangsan";
int age = 30;
rdf.writeBytes(name);
rdf.writeInt(age);
name = "lisi";
age = 22;
rdf.writeBytes(name);
rdf.writeInt(age);
name = "wangwu";
age = 32;
rdf.writeBytes(name);
rdf.writeInt(age);
rdf.close();
}
}