title: How can I write a sequence of strings and then a byte array to a file?
body: <p>I want to write first a sequence of strings and then a sequence of bytes into a file, using Java. I started by using <code>FileOutputStream</code> because of the array of bytes. After searching the API, I realised that <code>FileOutputStream</code> cannot write <code>String</code>s, only <code>int</code>s and <code>byte</code>s, so I switched to <code>DataOutputStream</code>. When I run the program, I get an exception. Why?</p>
  
  <p>Here's a portion of my code:</p>
  
  <pre><code> try {
              // Create the file
              FileOutputStream fos;
              DataOutputStream dos; // = new DataOutputStream("compressedfile.ecs_h");
              File file= new File("C:\\MyFile.txt");
              fos = new FileOutputStream(file);
              dos=new DataOutputStream(fos);
  
              /* saves the characters as a dictionary into the file before the binary seq*/
              for (int i = 0; i &lt; al.size(); i++) {
                  String name= al.get(i).name; //gets the string from a global arraylist, don't pay attention to this!
                  dos.writeChars(name); //saving the name in the file
              }
  
              System.out.println("\nIS SUCCESFULLY WRITTEN INTO FILE! ");
  
              dos.writeChars("&gt;&lt;");
              String strseq;
  
              /*write all elements from the arraylist into a string variable*/
              strseq= seq.toString();
              System.out.println("sTringSeq: " + strseq);
  
              /*transpose the sequence string into a byte array*/
              byte[] data = new byte[strseq.length() / 8];
  
              for (int i = 0; i &lt; data.length; i++) {
                  data[i] = (byte) Integer.parseInt(strseq.substring(i * 8, (i + 1) * 8), 2);
                  dos.write(data[i]);
              }
  
  
              dos.flush();
              //Close the output stream
              dos.close(); 
  } catch(Exception e){}
  </code></pre>