2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2019, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 3 of the GNU Lesser General Public License
7 * or later as published by the Free Software Foundation.
10 package eu.svjatoslav.commons.file;
14 public class IOHelper {
17 * Deletes files and directories recursively. WARNING!!! Follows symlinks!!!
19 * @param file directory to delete with entire contents.
20 * @throws IOException if filesystem error happens
22 public static void deleteRecursively(final File file) throws IOException {
23 if (file.isDirectory()) {
25 File[] files = file.listFiles();
27 throw new RuntimeException("Failed to read directory content for: "
30 for (final File subFile : files)
31 deleteRecursively(subFile);
34 throw new RuntimeException("Failed to delete directory: "
42 throw new FileNotFoundException("Failed to delete file: "
46 public static byte[] getFileContents(final File file)
49 final byte[] result = new byte[(int) file.length()];
50 try (final FileInputStream fileInputStream = new FileInputStream(file)) {
51 if (fileInputStream.read(result) != result.length)
52 throw new RuntimeException("Could not read file content:" + file);
57 public static String getFileContentsAsString(final File file)
60 return new String(getFileContents(file), "UTF-8");
61 } catch (final UnsupportedEncodingException exception) {
62 throw new RuntimeException(exception);
67 * Compares new file content with old file content. If content in equal,
68 * then leaves file as-is. If content differs, then overrides file with the
71 * @param file file to potentially overwrite
72 * @param newContent new content
73 * @return <code>true</code> if file was overwritten.
74 * @throws FileNotFoundException if file is not found.
75 * @throws IOException if error happens during file IO.
77 public static boolean overwriteFileIfContentDiffers(final File file,
78 final byte[] newContent) throws IOException {
82 if (file.length() == newContent.length) {
84 final byte[] oldContent = getFileContents(file);
86 for (int i = 0; i < newContent.length; i++)
87 if (newContent[i] != oldContent[i])
88 break checkForEquality;
90 // new file content in identical to old content
95 // New content differs from existing. Overwrite file.
96 saveToFile(file, newContent);
100 public static void saveToFile(final File file, final byte[] content)
102 try (final FileOutputStream fos = new FileOutputStream(file)) {