java 将文件中的姓名“李善”改为“王山”

一、需求

编写一个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();
    }
}

三、运行截图

处理前:
处理前

运行程序:
这里写图片描述

处理后:
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值