Java中文件的随机读写

时间:2023-03-09 09:25:02
Java中文件的随机读写
【例 10-12】模仿系统日志,将数据写入到文件尾部。
//********** ep10_12.java **********
import java.io.*;
class ep10_12{
public static void main(String args[]) throws IOException{
try{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String s=in.readLine();
RandomAccessFile myFile=new RandomAccessFile("ep10_12.log","rw");
myFile.seek(myFile.length()); //移动到文件结尾
myFile.writeBytes(s+"\n"); //写入数据
myFile.close();
}
catch(IOException e){}
}
}
程序运行后在目录中建立一个 ep10_12.log 的文件,每次运行时输入的内容都会在该文件内容的结尾处添加。