aspose file tools*
The moose likes I/O and Streams and the fly likes aCompletelySeriousTopicNameInvolvingReadingAFileInAsBinary Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "aCompletelySeriousTopicNameInvolvingReadingAFileInAsBinary" Watch "aCompletelySeriousTopicNameInvolvingReadingAFileInAsBinary" New topic
Author

aCompletelySeriousTopicNameInvolvingReadingAFileInAsBinary

jim jimmy jim jim jim
Greenhorn

Joined: Nov 23, 2011
Posts: 2
I would like to know how to read the binary of a file in java. I do not want to read just the contents of the file, I want to read the entire file itself as 0's and 1's. I've had a quick chat with Professor Google, but he just seems to point out examples of reading a files contents or advises me to buy car insurance.

Thank you for your time, I appreciate answers in any currency.

Lord Greenius Hornius III - Stirrer of tea, whipper of cream, and coffee bean crusher extraordinare!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19762
    
  20

Welcome to the Ranch!

Please UseAMeaningfulSubjectLine. "Ahem *cough*" doesn't say anything about your question. You can edit your post to change the subject line.

Back to your problem. You cannot read files bit-by-bit in Java. You can however read files byte-by-byte using InputStream (and FileInputStream), and it's read() method. If the return value is not -1 you have read one byte. You can then use the bitwise operators & and >> to get individual bits. For instance, to get the 2nd least significant bit you can use this code:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
jim jimmy jim jim jim
Greenhorn

Joined: Nov 23, 2011
Posts: 2
Ok, makes sense, so I can read the file in as bytes and then convert the bytes into bits. Thank you.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

jim jimmy jim jim jim wrote:Ok, makes sense, so I can read the file in as bytes and then convert the bytes into bits. Thank you.


You can't really "convert" a byte to bits as there is no bit data type in Java. You can manipulate the individual bits though, or put them into a BitSet, of create ints or chars with 0/1 or '0'/'1' values.

Can I ask why you want bits and what you plan to do with them? Depending on what you're doing, there may be a better approach.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: aCompletelySeriousTopicNameInvolvingReadingAFileInAsBinary