txt简单读写操作

        txt的读写代码,项目中在用的代码:

package xx.xx.xx.xx.utils;

import java.io.*;
import java.util.*;

/**
 * @Author xiarg
 * @CreateTime 2022/08/30  11:02
 */
public class TxtFileUtil {

    /**
     *
     * 一行一行读取文件,解决读取中文字符时出现乱码
     * @param filePath
     * @author :xiarg
     * @date : 2022/8/30 11:03
     */
    public static List<String> readFile(String filePath) {

        FileInputStream fis= null;
        InputStreamReader isr= null;
        BufferedReader br = null;
        List<String> resultList = new ArrayList<>();
        try {
            fis = new FileInputStream(filePath);
            isr = new InputStreamReader(fis, "UTF-8");
            br = new BufferedReader(isr);
            String line ;
            while ((line=br.readLine())!=null) {
                resultList.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //注意关闭的先后顺序,先打开的后关闭,后打开的先关闭
            try {
                if(null != br){
                    br.close();
                }
                if(null != isr){
                    isr.close();
                }
                if(null != fis){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultList;
    }

    /**
     *
     * 一行一行写入文件,解决写入中文字符时出现乱码
     * @param filePath
     * @author :xiarg
     * @date : 2022/8/30 11:03
     */
    public static void writeFile(String filePath,List<String> dataList) {
        File file = new File(filePath);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //写入中文字符时解决中文乱码问题
        FileOutputStream fos= null;
        OutputStreamWriter osw= null;
        BufferedWriter  bw= null;
        try {
            fos = new FileOutputStream(filePath,true);
            osw = new OutputStreamWriter(fos, "UTF-8");
            bw = new BufferedWriter(osw);

            for(String arr:dataList){
                bw.write(arr+"\t\n");
            }
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //注意关闭的先后顺序,先打开的后关闭,后打开的先关闭
            try {
                if(null != bw){
                    bw.close();
                }
                if(null != osw){
                    osw.close();
                }
                if(null != fos){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值