Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to write large String to a file

Tags:

java

string

file

I am trying to print a large string(single line) into a file. But the string is getting truncated in between. Any idea on why this is happening?

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();
    }   

}
like image 339
User27854 Avatar asked May 04 '16 12:05

User27854


1 Answers

You should remember to close the file.

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 and newer encapsulate that mechanism using 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();
}

Writing to any Writer can be buffered, leaving some of the data unwritten if you do not close it.

like image 177
OldCurmudgeon Avatar answered Oct 09 '22 00:10

OldCurmudgeon