Java BufferedWriter cannot write specific characters

I decided to test how many different characters I could write. I tried this code:

for (int i = 0;i < 255;i++) { myBufferedWriter.write(i); } 

But in the file, using my hex editor, I saw that it was usually considered first 01, 02, 03... , but then it reached 3F and wrote it about 20 times, and then continued to write normally. Can I write certain characters? I want to write all characters 0-255.

Full code:

 public class Main { public static void main(String[] args) { try{ BufferedWriter bw = new BufferedWriter(new FileWriter(new File("abc.txt"))); for (int i = 0;i < 255;i++) { bw.write(i); } bw.close(); }catch(Exception e){} } } 
+4
source share
2 answers

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 .

+4
source

I get it. My new code is:

 public class Main { public static void main(String[] args) { try{ DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File("abc.txt"))); for (int i = 0;i < 255;i++) dos.writeByte(i); dos.close(); }catch(Exception e){} } } 
0
source

Source: https://habr.com/ru/post/1489809/


All Articles