3

Is there a way to store some values in a binary file as C# does?

For example in C# it would be:

BinaryWriter bw = new BinaryWriter(MyFilStream);
bw.Write(data...);

And then, to read it like

BinaryReader br = new bla bla...;
br.ReadInt(file);

Is there a way to do this in Java? I'm Reading a lot of binary reading in Google, but I just find something of a JPG file, don't get it...

3
  • 1
    Check Serializable, ObjectInputStream and ObjectOutputStream. Commented Aug 12, 2014 at 19:11
  • 1
    Google: java binary file io, second entry ;) Commented Aug 12, 2014 at 19:13
  • Yes, you can write (and read) binary data. I suggest you look at DataOutputStream. Commented Aug 12, 2014 at 19:14

1 Answer 1

4

You could make use of DataOutputStream and/or DataInputStream to store and read binary data in Java.

Here is an example of how it's done:

import java.io.*;

public class Test{
    public static void main(String args[])throws IOException{

        DataInputStream d = new DataInputStream(new 
                                 FileInputStream("test.txt"));

        DataOutputStream out = new DataOutputStream(new 
                                 FileOutputStream("test1.txt"));

        String count;
        while((count = d.readLine()) != null){
            String u = count.toUpperCase();
            System.out.println(u);
            out.writeBytes(u + "  ,");
        }
        d.close();
        out.close();
    }
}

Editors' note:

.close() statements should be wrapped in finally block:

finally {
    d.close();
    out.close();
}

Source:
http://www.tutorialspoint.com/java/java_dataoutputstream.htm

Sign up to request clarification or add additional context in comments.

1 Comment

You should make sure you close your streams in a finally block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.