0

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?

Community
  • 1
  • 1
Prasanna
  • 2,593
  • 7
  • 39
  • 53

1 Answers1

2

The Java char type 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.

thkala
  • 84,049
  • 23
  • 157
  • 201