IO流 | IO流的应用举例

本文介绍三种文件操作方法:拷贝文件内容、在指定位置插入数据、读取并统计文件中出现次数最少的数据。涵盖核心代码实现及运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.将源文件路径下内容拷贝到目的路径文件中
/**
 * 源文件路径拷贝到目的路径文件中
 * @param srcFile 源文件
 * @param desFile 目的文件(目录/文件)
 */
public static void copyFile(String srcFile,String desFile){
    FileInputStream inputStream=null;
    FileOutputStream outputStream=null;
    File file1 = new File(desFile);
    try {
        inputStream = new FileInputStream(srcFile);
        outputStream = new FileOutputStream(desFile);
        byte[] bytes = new byte[100];
        int len;
        while((len=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //关闭资源
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果:
在这里插入图片描述

2.将数据插入到文件的指定位置
/**
 * 数据插入到文件的指定位置
 * @param srcFile 源文件
 * @param index 源文件内容要插入的位置
 * @param append 需要插入的内容
 */
public static void addContent(String srcFile,int index,String append){
    try {
        //将随机访问文件设置为可读可写属性
        RandomAccessFile accessFile = new RandomAccessFile(srcFile, "rw");

        //定义临时文件:存储插入位置后的内容
        String path="C:\\Users\\1\\Desktop\\test.txt";
        FileOutputStream file = new FileOutputStream(path);
        FileInputStream file1 = new FileInputStream(path);
        
        //将指针偏移至index位置处
        accessFile.seek(index);//5
        //确定指针位置
        System.out.println("偏移后指针位置在"+accessFile.getFilePointer());
        //将指针后的内容写入file中
        byte[] bytes = new byte[5];
        int read = accessFile.read(bytes, 0, 5);
        System.out.println("临时文件内容为:"+new String(bytes,0,read));
        file.write(bytes);
        //重新偏移指针,并添加数据
        accessFile.seek(index);
        accessFile.write(append.getBytes());
        //记录此时指针位置
        System.out.println("添加数据后指针位置在"+accessFile.getFilePointer());
        //将file文件内容拼接写入AccessFile中
        byte[] bytes2 = new byte[14];
        file1.read(bytes2);
        accessFile.write(bytes2);

        //指针回退
        accessFile.seek(0);
        byte[] bytes1 = new byte[14];
        int read1 = accessFile.read(bytes1);
        System.out.println("插入数据后,文件内容为:");
        System.out.println(new String(bytes1,0,read1));//helloniceworld
        file.close();
        file1.close();
        accessFile.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

运行结果及文件内容显示:
在这里插入图片描述在这里插入图片描述

3.读取文件,求出现次数最少的5组数据
public static void readFile(String path){
    try {
        //创建字符输入缓冲流实例
        FileReader reader = new FileReader(path);
        BufferedReader br = new BufferedReader(reader);//将数据写入用户空间的缓冲区
        ArrayList<Integer> arrayList = new ArrayList<>();

        String str;
        int i;
        //向ArrayList中添加数据,添加原则:依次读取每行数据,以","分割
        while((str=br.readLine())!=null){
            String[] s=str.split(",");
            for(i=0;i<s.length;i++) {
                arrayList.add(Integer.valueOf(s[i]));
            }
        }

        //hashMap统计出现的次数
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        Iterator<Integer> iterator = arrayList.iterator();
        while(iterator.hasNext()){
            Integer next=iterator.next();
            if(hashMap.containsKey(next)){
                hashMap.put(next,hashMap.get(next)+1);
            }else{
                hashMap.put(next,1);
            }
        }

        Comparator<Map.Entry<Integer, Integer>> com = new Comparator<Map.Entry<Integer, Integer>>() {
            //重写compare方法 要求:比较节点value值 从小到大
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        };

        //将节点放入优先级队列中,获取最小的5个
        PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(5,com);//大根堆
        Iterator<Map.Entry<Integer, Integer>> iterator1 = hashMap.entrySet().iterator();
        while(iterator1.hasNext()){
            Map.Entry<Integer, Integer> entry = iterator1.next();
            if(queue.size()<5){
                queue.add(entry);
            }else{
                Map.Entry<Integer, Integer> entry1=queue.peek();//取出队顶元素,即队列中的最小值
                //当前元素value值小于队顶元素
                if(entry.getValue()<entry1.getValue()){
                    queue.poll();//删除队顶
                    queue.add(entry);//此时entry为queue的队顶元素
                }
            }
        }
        System.out.println("出现次数最少的5组数据如下");
        Iterator<Map.Entry<Integer, Integer>> iterator2 = queue.iterator();
        while(iterator2.hasNext()){
            Map.Entry <Integer, Integer> entry = iterator2.next();
            System.out.println(entry.getKey()+":"+entry.getValue());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值