Java 读写txt文件

实现两个功能

1.逐行读取txt文件,并以"," 逗号位分隔符 ,把读到的内容转为map或者实体类。text文件不能有空行转为map, key 一样的会更新时,例如有10行内容,其中两行key一样,那么map长度为9.

2.把内容 写入txt文件

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TxtUtils {

    static Logger logger = LoggerFactory.getLogger(TxtUtils.class);

    public static void main(String[] args) throws IOException {

        //测试读文件,并把文件内容逐行打印出来,把每行内容转为一个map或object
        String filePath = "C:\\Test\\test.txt";
        readTxt(filePath);

        //测试写入text文件
        String fileParent = "C:\\Test";
        String filename1 = "test1.txt";

        String message = "this is message \n";
        for (int i = 0; i < 3; i++) {
            message += "abc \n";
        }
         writetoTxt1(fileParent, filename1, message);
        
        //测试写入text文件
        String fileName2 = "test2.txt";
        
        List<String> messageList = new ArrayList<>();
        messageList.add("ok,0");
        messageList.add("no,1");
        messageList.add("pass,2");
        messageList.add("okay,3");

        writeToTxt(fileParent, fileName2, messageList);
    }

    /**
     * 逐行读取TXT并处理,打印到控制台, 并转为Map或者其它Object
     *
     * @throws IOException
     */
    public static void readTxt(String filePath) throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8"));
        String lineTxt = null;
        int count = 0;
        // 逐行读取
        while ((lineTxt = br.readLine()) != null) {
            // 每行数据以逗号分隔
            String[] names = lineTxt.split(",");
            // 处理数据, 可以转成entity, 在这儿转换成map
            map.put(names[0], names[1]);
            // 输出内容到控制台
            logger.info(lineTxt);
            count++;
        }
        br.close();
        logger.info("map.size()=" + map.size());
        logger.info("count=" + count);
    }


    //写入整个string
    public static void writetoTxt1(String fileParent, String filename, String message) throws IOException {

        File dir = new File(fileParent);
        dir.mkdirs();

        File file = new File(fileParent + File.separator + filename);
        file.createNewFile();
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(message);
        out.flush();

    }

    // 逐行写入List<String>
    public static void writeToTxt(String fileParent, String file, List<String> messageList) throws FileNotFoundException {

        File dir = new File(fileParent);
        dir.mkdirs();

        FileOutputStream fos = new FileOutputStream(fileParent + File.separator + file);
        
        PrintWriter pw = new PrintWriter(fos);
        for (String message : messageList) {
            pw.println(message);
        }
        pw.close();

    }

}
View Code

 

posted on 2021-01-06 15:25  dreamstar  阅读(7253)  评论(0编辑  收藏  举报