Search code examples
javafilereaderbitsetbytearrayoutputstream

How to get the bitset back from a file saved as bytearrayoutputstream in java?


I created a BitSet called b and saved it to a file using this code snippet in java.

    byte[] bs = b.toByteArray();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(bs);
    FileOutputStream fr_out = new FileOutputStream("output.txt");
    baos.writeTo(fr_out);

Now can anyone help me figure out how to read this "output.txt" file and get back the BitSet "b"?

Thanks

Edit in regard to this question being marked as duplicate: The above given link might have a solution as part of the discussion people had in their comments, but not in the actual answer text-field. Not to mention, the above question does not reference to the question as to how we can get a BitSet, it only talks about how to get a byte back. Indeed it was altogether another problem that I was facing a day ago, but this question is completely different from that one as I explained above. So I would like to ask the community and the person/s to reconsider their action of marking this question as duplicate with another question of mine itself.

TLDR: This question asked what's 2 + 2 = ?, and the other question asked what's 2 * 2 = ?, but while answering 2 * 2, someone also happened to answer 2 + 2 = ? (it took me hours to find the solution and I did it from another link, not the one posted above), just because answers are similar doesn't mean questions are and above all, I don't want any programmer to keep searching for things for hours when they could just look up this question and find out how to do things, instead of going through the entire web.

Thanks.


Solution

  • Since there are no answers yet, I would like to post one of the ways that I sorted this out, however it would be great if someone more experienced could give a better solution. Here is what I did to get back my BitSet from the file (to which I wrote a BitSet using toByteArray() method and ByteArrayOutputStream).

        Path path = Paths.get("output.txt");
        byte[] ans = Files.readAllBytes(path);
        BitSet bits = BitSet.valueOf(ans);
    

    Now bits has the original BitSet.