多线程处理文件

本文介绍了一种使用Java进行文件读写的方法,包括如何读取文件内容并将其分割成列表,以及如何将列表内容写回文件。此外,还提供了一个简单的线程处理示例,用于演示如何在读取和写入文件时利用多线程提高效率。

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

package com.geotmt.zxw.utils;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import com.google.common.io.Files;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;

/**
 *
 * Created by geo on 2018/12/3. */
@Slf4j
public class FileUtil2 {

    /**
     * 读取文件(前提内存允许)
     *
     * @param filePathAndName 文件路径及名称
     */
    static List<String> readFileAndSpilt(String filePathAndName) {
        String encoding = "utf-8";
        List<String> txtList = Lists.newArrayList();
        File file = new File(filePathAndName);
        try {
            if (file.isFile() && file.exists()) { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    txtList.add(lineTxt) ;
                }
                read.close();
            } else {
                log.info("找不到指定的文件");
            }
        } catch (Exception e) {
            log.info("读取文件内容出错:",e);
        }
        return txtList ;
    }

    /**
     * 写文件
     * @param txtList 文件
     * @param outFilePathAndName 输出路径
     */
    static void writeTxt(List<String> txtList,String outFilePathAndName){
        File spiltFilePathAndNameFile = new File(outFilePathAndName) ;
        File path = new File(outFilePathAndName.substring(0,outFilePathAndName.lastIndexOf("/"))) ;
        if(!path.exists()){
            try {
                boolean newFile = path.mkdirs();
                log.info("创建目录[{}]结果[{}].",path.getPath(),newFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            boolean newFile = spiltFilePathAndNameFile.createNewFile() ;
            log.info("创建文件[{}]结果[{}].",outFilePathAndName,newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 数组转换文件,按照行分割
        StringBuffer sb = new StringBuffer() ;
        txtList.forEach(v -> sb.append(v).append("\n"));
        smallFileWrite(outFilePathAndName,sb.toString()) ;
    }

    /**
     * 演示向文件中写入字节流
     *
     * @param fileName 要写入文件的文件名
     * @param contents 要写入的文件内容
     */
    static void smallFileWrite(final String fileName, final String contents){
        try{
            final File newFile = new File(fileName);
            Files.write(contents.getBytes(), newFile);
        }catch (Exception e){
            log.info(  "ERROR trying to write to file [{}]",fileName,e);
        }
    }

    /**
     * 其他操作,即睡10ms
     * @param line 文本行
     * @return 处理过的文本行
     */
    static String otherOper(String line){
        try {
            Thread.sleep(10);
        }catch (Exception e){
            e.printStackTrace();
        }
        return line + System.currentTimeMillis() ;
    }

    /**
     * 处理方法
     *
     * @param stringList List<String>
     * @return List<String>
     */
    static List<String> handle(List<String> stringList,List<String> resultList) {
        FutureTask<List<String>> task = new FutureTask<>(()->stringList.stream().map(FileUtil2::otherOper).collect(Collectors.toList()));
        new Thread(task).start() ;
        try {
            resultList.addAll(task.get()) ;
            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
            return null ;
        }
    }

    public static void main(String[] args) {
        int thredNum = 10 ; // 线程数
        String filePathAndName = "" ; // 文件路径
        String outFilePathAndName = ""; // 输出路径
        List<String> resultList = Collections.synchronizedList(Lists.newArrayList()) ;
        List<String> txtList = readFileAndSpilt(filePathAndName) ; // 读取文本,前提是文件不能超出堆的承受能力
        List<List<String>> txtLists = Lists.partition(txtList, thredNum); // 线程数切割
        txtLists.forEach(list ->handle(list,resultList)); // 处理文本
        writeTxt(txtList,outFilePathAndName) ; // 输出结果
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值