title: Reading and writing bytes from/to a file
body: <p>I'm trying to write an array of bytes to a file and read them afterwards. It's important that the the array of bytes that I write is the same as the one that I read. I tried some methods that were suggested here (<a href="https://stackoverflow.com/questions/858980/file-to-byte-in-java">File to byte[] in Java</a>). However when I apply them I end up reading a different array that I initially wrote.</p>
  
  <p>Here's what i tried:</p>
  
  <pre><code>import java.io.File;
  //import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  
  //import java.nio.file.Files;
  //import java.nio.file.Path;
  //import java.nio.file.Paths;
  import org.apache.commons.io.*;
  
  public class FileConverter {
  
      public static void ToFile(byte[] bytes, String pathName) throws IOException{
          FileOutputStream f = new FileOutputStream(pathName);
          f.write(bytes);
          f.close();
      }
  
      public static byte[] ToBytes(String pathName) throws IOException{
          //Path path = Paths.get(pathName);
          //byte[] bytes = Files.readAllBytes(path);
  
          //FileInputStream f = new FileInputStream(pathName);
          //byte[] bytes = IOUtils.toByteArray(f);
  
          File file = new File(pathName);
          byte[] bytes = FileUtils.readFileToByteArray(file);
          return bytes;
      }
  
  }
  </code></pre>
  
  <p>my test class:</p>
  
  <pre><code>import java.io.IOException;
  import org.junit.Assert;
  import org.junit.Test;
  
  public class FileConverterTest {
  
      @Test
      public void leesSchrijf() throws IOException{
          String test = "test";
          String pathName = "C://temp//testFile";
          byte[] bytes = test.getBytes();
          FileConverter.ToFile(bytes, pathName);
          Assert.assertEquals(bytes, FileConverter.ToBytes(pathName));
     } 
  }
  </code></pre>
  
  <p>Whenever I execute the test class my results vary and the arrays never match.
  e.g. java.lang.AssertionError: expected:&lt;[B@a3a7a74> but was:&lt;[B@53d5aeb> (first execution)</p>
  
  <p>java.lang.AssertionError: expected:&lt;[B@29643eec> but was:&lt;[B@745f0d2e> (next execution)</p>
  
  <p>I'm fairly new to test classes and I'm no java genius. So I wondered whether I was doing something incorrectly. If not, is there a way to preserve the byte array while writing it to a file?</p>