Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing a BitSet to a file in java

I have a BitSet and want to write it to a file- I came across a solution to use a ObjectOutputStream using the writeObject method.

I looked at the ObjectOutputStream in the java API and saw that you can write other things (byte, int, short etc)

I tried to check out the class so I tried to write a byte to a file using the following code but the result gives me a file with 7 bytes instead of 1 byte

my question is what are the first 6 bytes in the file? why are they there?

my question is relevant to a BitSet because i don't want to start writing lots of data to a file and realize I have random bytes inserted in the file without knowing what they are.

here is the code:

    byte[] bt = new byte[]{'A'};
    File outFile = new File("testOut.txt");
    FileOutputStream fos = new FileOutputStream(outFile);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.write(bt);
    oos.close();

thanks for any help

Avner

like image 342
Avner Avatar asked Sep 04 '09 09:09

Avner


People also ask

How do I write a byte array to a file?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.

How does BitSet work in Java?

Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

How do you write bytes in Java?

byte Syntax in JAVA:byte Variable_Name = Value; For example: byte x = 10; Here x is variable name and 10 is a value assigned to a variable integer data type byte.

What is the difference between a regular array and a BitSet in Java?

The difference between a boolean array and a BitSet is essentially the same as the difference between an array of object references and a List.


1 Answers

The other bytes will be type information.

Basically ObjectOutputStream is a class used to write Serializable objects to some destination (usually a file). It makes more sense if you think about InputObjectStream. It has a readObject() method on it. How does Java know what Object to instantiate? Easy: there is type information in there.

like image 76
cletus Avatar answered Oct 01 '22 08:10

cletus