title: How to calculate hash value of a file in Java?
body: <p>I wrote the following program to calculate SHA-256 hash value of a string in Java:</p>
  
  <pre><code>public class ToHash {
  
      public static void main(String[] args)  {
  
          byte[] data = "test".getBytes("UTF8");
          MessageDigest digest = MessageDigest.getInstance("SHA-256");
          byte[] hash = digest.digest(data);
          System.out.println(new BASE64Encoder().encode(hash));
  
      }
  }
  </code></pre>
  
  <p>Well, that works fine. In the next step I want to develop it in a way to accept a file and calculate its hash value. My solution is to read whole the file in a string array and the call the <code>digest()</code> method on that string array. But there are two problems :</p>
  
  <ol>
  <li><p>I don't have any idea how to read whole the file into an array? Currently I think I must read it line by line and append an array with the new lines!</p></li>
  <li><p>Above methodology  need a lot of memory for big files!</p></li>
  </ol>
  
  <hr>
  
  <p>This is my current program to read a file:</p>
  
  <pre><code>public class ToHash {
  
      public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, FileNotFoundException, IOException {
          // TODO code application logic here
  
          // The name of the file to open.
          String fileName = "C:\\Users\\ghasemi\\Desktop\\1.png";
          BufferedReader br = null;
  
          try {
  
              String sCurrentLine;
              br = new BufferedReader(new FileReader(fileName));
              while ((sCurrentLine = br.readLine()) != null) {
                  byte[] data = sCurrentLine.getBytes("UTF8");
                  System.out.println(new BASE64Encoder().encode(data));
              }
  
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              try {
                  if (br != null) {
                      br.close();
                  }
              } catch (IOException ex) {
                  ex.printStackTrace();
              }
          }
  
      }
  }
  </code></pre>
  
  <p>It seems that there is no method for <code>BufferedReader</code> object to read whole the file with one call.</p>