For large strings (60MB or so long), FileWriter is appending extra nulls to the end of my files. For small strings this code works as expected.
For clarity, dat and filePath are Strings.
FileWriter fstream = new FileWriter( filePath );
fstream.write( dat );
fstream.close();
File f = new File( filePath );
System.out.println("Data: " + dat.length() + ", File: " + f.length());
In short, under what circumstances, should the two printed values be different?
Here’s my example output:
Data: 63833144, File: 63833728
I got 584 extra nulls at the end of file for some reason. I find it reasonable that the string might be over allocated, but these shouldn’t print to file, right ? To make things worse, if I explicitly give it the length:
fstream.write(dat, 0, dat.length());
The behavior is the same. Coincidentally, if I say (dat.length() – 584), it does what I want, but only in this specific case.
Any ideas?
JDK version: 1.7.0_02
Edited: Add file types for variables (both Strings)
The file length depends on encoding. This test
will show the length in bytes after encoding, because
String.getByteswill use the same encoding (default) asnew FileWriter(file)