I think your problem is that you are using the wrong API. What happens to your current code is that your “characters” are treated as text and encoded using the default encoding for your platform.
If you want to write data in binary form (for example, with bytes from 0 to 255), you should use the OutputStream API. In particular, BufferedOutputStream .
For instance:
public class Main { public static void main(String[] args) throws IOException { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(new File("abc.dat"))); for (int i = 0; i < 255; i++) { bos.write(i); } bos.close(); } }
If you also want to write other data types (in binary form), then DataOutputStream more suitable ... because it has a bunch of other methods for writing primitive types, etc. However, if you want to write efficiently, you will need a BufferedOutputStream between FileOutputStream and DataOutputStream .
source share