欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FileWriter字符流写入缓存限制

程序员文章站 2022-07-15 13:45:28
...

在操作文件字符读写的时候,出现了文字写入不全的情况,经过检查,发现FileWriter存在写入大小限制,最大为24KB,如图



FileWriter字符流写入缓存限制


FileWriter字符流写入缓存限制


代码如下:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

/**
 * 作者:Haibo.Liu
 * 描述:
 * 日期: 2017/5/8
 * QQ:836915746
 */
public class GetXml2 {

    private static String pathLog = "C:\\Users\\Haibo\\Desktop\\1_show_ziwojieshao.xml";//xml路径1
    private static String pathXml = "C:\\Users\\Haibo\\Desktop\\1111.xml";//xml路径2

    public static void main(String[] args) throws Exception {
        //清空文件
        FileWriter writer = new FileWriter(pathXml);
        writer.write("");
        writer.close();

        FileWriter writerTo = new FileWriter(pathXml, true);

        FileReader fr = new FileReader(pathLog);//获取文件流
        BufferedReader br = new BufferedReader(fr); //将流整体读取。
        String str;

        int action = 1;
        double actionTime = 0;
        while ((str = br.readLine()) != null) {//判断是否是最后一行
            if (str.indexOf("actionGroup actionTime") != -1) {
                int a = str.indexOf("\"", 0);
                int b = str.indexOf("\"", a+1);
                double time = Double.parseDouble(str.substring(a+1,b));
                writerTo.write("\t<actionGroup actionTime = \""+(time-96)+"\">\r\n");

            }else {
                writerTo.write(str+"\r\n");
            }
        }
        System.out.println("Finish");
    }
}

解决方案,在每次写入的时候flush()一下


修改后代码


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

/**
 * 作者:Haibo.Liu
 * 描述:
 * 日期: 2017/5/8
 * QQ:836915746
 */
public class GetXml2 {

    private static String pathLog = "C:\\Users\\Haibo\\Desktop\\1_show_ziwojieshao.xml";//xml路径1
    private static String pathXml = "C:\\Users\\Haibo\\Desktop\\1111.xml";//xml路径2

    public static void main(String[] args) throws Exception {
        //清空文件
        FileWriter writer = new FileWriter(pathXml);
        writer.write("");
        writer.close();

        FileWriter writerTo = new FileWriter(pathXml, true);

        FileReader fr = new FileReader(pathLog);//获取文件流
        BufferedReader br = new BufferedReader(fr); //将流整体读取。
        String str;

        int action = 1;
        double actionTime = 0;
        while ((str = br.readLine()) != null) {//判断是否是最后一行
            if (str.indexOf("actionGroup actionTime") != -1) {
                int a = str.indexOf("\"", 0);
                int b = str.indexOf("\"", a+1);
                double time = Double.parseDouble(str.substring(a+1,b));
                writerTo.write("\t<actionGroup actionTime = \""+(time-96)+"\">\r\n");

            }else {
                writerTo.write(str+"\r\n");
            }
            writerTo.flush();
        }
        System.out.println("Finish");
    }
}