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!
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:
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.