View Javadoc
1   /*
2    * SPDX-License-Identifier: Apache-2.0
3    * See LICENSE file for details.
4    *
5    * Copyright 2025-2026 Hazendaz
6    * Copyright 2011-2025 Acegi Technology Pty Limited.
7    */
8   package au.com.acegi.xmlformat;
9   
10  import java.io.File;
11  import java.io.IOException;
12  import java.io.InputStream;
13  import java.nio.file.Files;
14  import java.util.zip.CRC32;
15  import java.util.zip.CheckedInputStream;
16  import java.util.zip.Checksum;
17  
18  /**
19   * Utility methods for dealing with I/O resources.
20   */
21  final class IOUtil {
22  
23      private IOUtil() {
24      }
25  
26      /**
27       * Returns a CRC32 of the provided input stream.
28       *
29       * @param in
30       *            to CRC32
31       *
32       * @return the CRC32 value
33       *
34       * @throws IOException
35       *             if unable to read the input stream
36       */
37      @SuppressWarnings("PMD.EmptyWhileStmt")
38      static long hash(final InputStream in) throws IOException {
39          final Checksum cksum = new CRC32();
40          final CheckedInputStream is = new CheckedInputStream(in, cksum);
41          final byte[] buff = new byte[4_096];
42          while (is.read(buff) >= 0) {
43              // CheckInputStream will update its internal checksum
44          }
45          return is.getChecksum().getValue();
46      }
47  
48      /**
49       * Returns a CRC32 of the given file.
50       *
51       * @param file
52       *            to CRC32
53       *
54       * @return the CRC32 value
55       *
56       * @throws IOException
57       *             if unable to read the file
58       */
59      static long hash(final File file) throws IOException {
60          try (InputStream fis = Files.newInputStream(file.toPath())) {
61              return hash(fis);
62          }
63      }
64  
65  }