FileWriter字符流写入缓存限制
程序员文章站
2022-07-15 13:45:28
...
在操作文件字符读写的时候,出现了文字写入不全的情况,经过检查,发现FileWriter存在写入大小限制,最大为24KB,如图
代码如下:
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");
}
}
上一篇: 关于浮点数丢失精度的原理