Susan Yanders
Susan Yanders

Reputation: 874

Java BufferedWriter can't write certain characters

I decided to do a test for 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 it counted normally at first 01, 02, 03..., but then it got to 3F, and wrote that around 20 times, and then continued writing normally. Can I not write certain characters? I want to be able 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){}
    }
}

Upvotes: 4

Views: 1684

Answers (2)

Stephen C
Stephen C

Reputation: 718826

I think your problem is that you are using the wrong API. What is happening with your current code is that your "characters" are being treated as text and encoded using the default character encoding for your platform.

If you want to write data in binary form (e.g. the bytes zero through 255) then you should be using the OutputStream APIs. Specifically BufferedOutputStream.

For example:

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 want to be able to write other data types too (in binary form), then DataOutputStream is more appropriate ... because it has a bunch of other methods for writing primitive types and so on. However, if you want to write efficiently you need a BufferedOutputStream in between the FileOutputStream and the DataOutputStream.

Upvotes: 4

Susan Yanders
Susan Yanders

Reputation: 874

I figured it out. My new code:

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){}
    }
}

Upvotes: 0

Related Questions