BufferedReader和BufferedWriter对文本文件实现处理每一行内容

BufferedReader和BufferedWriter对文本文件实现处理每一行内容

记住怎么创建Reader和Writer就行了,用完记得关流。

package com.czxy.demo06;

import java.io.*;
import java.util.stream.Stream;

/**
 * 练习题
 * 第一步:数据预处理阶段
 */
public class DataConvert01 {
    public static void main(String[] args) throws IOException {

        //创建文件输入流,等下BufferedReader要用
        FileInputStream fileInputStream = new FileInputStream(new File("E:\\cache\\JavaOutput\\input\\20191231\\video.txt"));

        //BufferedReader() ==> InputStreamReader() ==> FileInputStreamReader() ==> File()
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

        //BufferedWriter() ==> FileWriter("文件路径")
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("E:\\cache\\JavaOutput\\output\\20191231\\video2.txt"));



        //读取文件的所有行
        while (true){
            //读一行
            String str = bufferedReader.readLine();

            System.out.println(str);

            //如果读到空行说明到达文件尾,就退出
            if (str == null){
                break;
            }

            if (str.contains("&")){
                //用&分割
                String[] split = str.split("&");
                String left = split[0].trim();
                String right = split[1].trim();

                String newStr = left+":"+right;

                String resultStr = newStr.replace(":", ",");
                bufferedWriter.write(resultStr);
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }else {
                String replace = str.replace(":", ",");
                bufferedWriter.write(replace);
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }

        }
        bufferedReader.close();
        bufferedWriter.close();


    }
}