Possible Duplicate:
Create file with given size in Java
Say, I want to create a file of size 1KB, will this approach work?
I create a java array like
char[] s = new char[1024]; //1KByte
and write it to a newly created *.txt file using a writer, will the size of the file be 1Kb precisely? If not, how should i create a file of the desired size?
The Java
chartype is 16-bits long and OutputStreamWriter objects are string-oriented, not byte-oriented. Depending on the output encoding of the writer, you could get e.g. a 2 KB file, or even something unpredictable on character sets with a variable number of bytes per character.You would be better off using an OutputStream directly, either with a
byte[]or using write(int) in a loop. That would guarantee that you get what you are asking for.