Note that there are some explanatory texts on larger screens.

plurals
  1. POJava read into byte array
    text
    copied!<p>I have a .txt file consisting of 1's and 0's like so;</p> <pre><code>11111100000001010000000101110010 11111100000001100000000101110010 00000000101001100010000000100000 </code></pre> <p>I would like to be able to read 8 (1's and 0's) and put each 'byte' into a byte array. So a line would be 4 bytes;</p> <pre><code>11111100 00000101 00000001 01110010 --&gt; 4 bytes, line 1 11111100 00000110 00000001 01110010 --&gt; 8 bytes, line 2 00000000 10100110 00100000 00100000 --&gt; total 12 bytes, line 3 ... and so on. </code></pre> <p>I believe I need to store the data in a binary file but I'm not sure how to do this. Any help is greatly appreciated.</p> <p>Edit 1:</p> <p>I would like to put 8 1's and 0's (11111100, 00000101) into a byte and store in a byte array so 11111100 would be the first byte in the array, 00000101 the second and so on. I hope this is clearer.</p> <p>Edit 2:</p> <pre><code>fileopen = new JFileChooser(System.getProperty("user.dir") + "/Example programs"); // open file from current directory filter = new FileNameExtensionFilter(".txt", "txt"); fileopen.addChoosableFileFilter(filter); if (fileopen.showOpenDialog(null)== JFileChooser.APPROVE_OPTION) { try { file = fileopen.getSelectedFile(); //create FileInputStream object FileInputStream fin = new FileInputStream(file); byte[] fileContent = new byte[(int)file.length()]; fin.read(fileContent); for(int i = 0; i &lt; fileContent.length; i++) { System.out.println("bit " + i + "= " + fileContent[i]); } //create string from byte array String strFileContent = new String(fileContent); System.out.println("File content : "); System.out.println(strFileContent); } catch(FileNotFoundException e){} catch(IOException e){} } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload