一、需求
编写一个Java源程序,其中的文件读写部分使用RandomAccessFile类来完成,程序实现的功能如下:
编写一个包含主方法main的公共类(访问权限为public的类),主方法main中完成的任务是:
(1)将实验6产生的文件“lianxi1.txt”中的姓名“李善”改为“王山”。
(2)在文件“lianxi1.txt”原有信息之后继续添加学生信息。
二、代码
public class exp7
{
public static void main(String[] args) throws IOException
{
//获取标准输入流
InputStream inputStream = System.in;
//定义字符转换流
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
//定义一个缓冲字符流接收文件名
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//提示用户输入文件名
System.out.println("请输入要处理的文件名:");
//读取用户输入的用户名
String filename = bufferedReader.readLine();
//创建文件对象
File file = new File(filename);
//创建随机读写流对象
RandomAccessFile accessFile = new RandomAccessFile(file,"rw");
System.out.println("本程序的任务是:\n1.将“"+file.getName()+"”中的姓名“李善”改为“王山”。\n2.在“"+file.getName()+"”中原有信息之后继续添加学生信息。");
//获取文件长度
long length = accessFile.length();
//定义当前读取的位置
long position = 0;
//记录读取前的位置
long index = 0;
//将读取位置定位到文件头部
accessFile.seek(position);
while(position<length)
{
index = accessFile.getFilePointer();
//读取内容
String content = accessFile.readLine();
//重新编码
byte[] buff = content.getBytes("iso-8859-1");//因为iso-8859-1码表是唯一一个编满的,所以用他编码不会丢数据
//使用当前机器的默认编码方式将字节数组转化成字符串
content = new String(buff);
if(content.startsWith("李善"))
{
//content.replaceFirst("李善", "王山"); //不知道为啥用replace不起作用
//修改姓名
content = "王山"+content.substring("李善".length(), content.length());
//重新定位指针
accessFile.seek(index);
//写入数据
accessFile.write(content.getBytes());
}
position = accessFile.getFilePointer();
}
accessFile.close();
System.out.println("文件“"+file.getName()+"”中的姓名“李善”已经改为“王山”,请查阅!");
System.out.println("请继续向文件“"+file.getName()+"”中添加文件新的文件信息,以finish结束。");
//创建随机读写流对象
RandomAccessFile accessFile2 = new RandomAccessFile(file,"rw");
//追加内容时指针定位到文件末尾
accessFile2.seek(accessFile2.length());
String content = new String();
while(!"finish".equals(content = bufferedReader.readLine()))
{
accessFile2.write(("\r\n"+content).getBytes());
accessFile2.seek(accessFile2.length());
}
accessFile2.close();
}
}
三、运行截图
处理前:
运行程序:
处理后: