2 * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.commons.file;
9 public class IOHelper {
12 * Deletes files and directories recursively. WARNING!!! Follows symlinks!!!
14 * @param file directory to delete with entire contents.
15 * @throws IOException if filesystem error happens
17 public static void deleteRecursively(final File file) throws IOException {
18 if (file.isDirectory()) {
20 File[] files = file.listFiles();
22 throw new RuntimeException("Failed to read directory content for: "
25 for (final File subFile : files)
26 deleteRecursively(subFile);
29 throw new RuntimeException("Failed to delete directory: "
37 throw new FileNotFoundException("Failed to delete file: "
41 public static byte[] getFileContents(final File file)
44 final byte[] result = new byte[(int) file.length()];
45 try (final FileInputStream fileInputStream = new FileInputStream(file)) {
46 if (fileInputStream.read(result) != result.length)
47 throw new RuntimeException("Could not read file content:" + file);
52 public static String getFileContentsAsString(final File file)
55 return new String(getFileContents(file), "UTF-8");
56 } catch (final UnsupportedEncodingException exception) {
57 throw new RuntimeException(exception);
62 * Compares new file content with old file content. If content in equal,
63 * then leaves file as-is. If content differs, then overrides file with the
66 * @param file file to potentially overwrite
67 * @param newContent new content
68 * @return <code>true</code> if file was overwritten.
69 * @throws FileNotFoundException if file is not found.
70 * @throws IOException if error happens during file IO.
72 public static boolean overwriteFileIfContentDiffers(final File file,
73 final byte[] newContent) throws IOException {
77 if (file.length() == newContent.length) {
79 final byte[] oldContent = getFileContents(file);
81 for (int i = 0; i < newContent.length; i++)
82 if (newContent[i] != oldContent[i])
83 break checkForEquality;
85 // new file content in identical to old content
90 // New content differs from existing. Overwrite file.
91 saveToFile(file, newContent);
95 public static void saveToFile(final File file, final byte[] content)
97 try (final FileOutputStream fos = new FileOutputStream(file)) {