无法将大型String写入文件

时间:2016-05-04 12:55:51

标签: java string file

我正在尝试将大字符串(单行)打印到文件中。但是字符串在两者之间被截断了。对于为什么会发生这种情况的任何想法?

void writeToFile(String schemaString,String message){

    try{
        FileWriter fw = new FileWriter("D:\\Servicelog.txt", true);                     
        java.util.Date date= new java.util.Date();
        fw.write(new Timestamp(date.getTime())+"\n");
        fw.write(message+"\n");         
        fw.write("schemaBegins\n"+schemaString+"\n"+"schemaEnds");
    }catch(Exception e){
        e.printStackTrace();
    }   

}

1 个答案:

答案 0 :(得分:8)

你应该记得关闭文件。

FileWriter fw = null;
try {
    fw = new FileWriter("D:\\Servicelog.txt", true);
    java.util.Date date = new java.util.Date();
    fw.write(new Timestamp(date.getTime()) + "\n");
    fw.write(message + "\n");
    fw.write("schemaBegins\n" + schemaString + "\n" + "schemaEnds");
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if ( fw != null ) {
        fw.close();
    }
}

Java7和更新版使用try-with-resources封装了该机制:

try (FileWriter fw = new FileWriter("D:\\Servicelog.txt", true) ) {
    java.util.Date date = new java.util.Date();
    fw.write(new Timestamp(date.getTime()) + "\n");
    fw.write(message + "\n");
    fw.write("schemaBegins\n" + schemaString + "\n" + "schemaEnds");
} catch (Exception e) {
    e.printStackTrace();
}

可以缓冲对任何Writer的写入,如果不关闭,则会留下一些未写入的数据。