1 /*
2 * XML Format Maven Plugin (https://github.com/acegi/xml-format-maven-plugin)
3 *
4 * Copyright 2011-2025 Acegi Technology Pty Limited.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * https://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package au.com.acegi.xmlformat;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.nio.file.Files;
24 import java.util.zip.CRC32;
25 import java.util.zip.CheckedInputStream;
26 import java.util.zip.Checksum;
27
28 /**
29 * Utility methods for dealing with I/O resources.
30 */
31 final class IOUtil {
32
33 private IOUtil() {
34 }
35
36 /**
37 * Returns a CRC32 of the provided input stream.
38 *
39 * @param in
40 * to CRC32
41 *
42 * @return the CRC32 value
43 *
44 * @throws IOException
45 * if unable to read the input stream
46 */
47 @SuppressWarnings("PMD.EmptyWhileStmt")
48 static long hash(final InputStream in) throws IOException {
49 final Checksum cksum = new CRC32();
50 final CheckedInputStream is = new CheckedInputStream(in, cksum);
51 final byte[] buff = new byte[4_096];
52 while (is.read(buff) >= 0) {
53 // CheckInputStream will update its internal checksum
54 }
55 return is.getChecksum().getValue();
56 }
57
58 /**
59 * Returns a CRC32 of the given file.
60 *
61 * @param file
62 * to CRC32
63 *
64 * @return the CRC32 value
65 *
66 * @throws IOException
67 * if unable to read the file
68 */
69 static long hash(final File file) throws IOException {
70 try (InputStream fis = Files.newInputStream(file.toPath())) {
71 return hash(fis);
72 }
73 }
74
75 }