2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2014, 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;
13 import java.io.FileInputStream;
14 import java.io.FileNotFoundException;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17 import java.io.UnsupportedEncodingException;
19 public class IOHelper {
22 * Deletes files and directories recursively. WARNING!!! Follows symlinks!!!
25 * directory to delete with entire contents.
28 * if filesystem error happens
30 public static void deleteRecursively(final File file) throws IOException {
31 if (file.isDirectory()) {
33 for (final File subFile : file.listFiles())
34 deleteRecursively(subFile);
37 throw new FileNotFoundException("Failed to delete directory: "
45 throw new FileNotFoundException("Failed to delete file: "
49 public static byte[] getFileContents(final File file)
50 throws FileNotFoundException, IOException {
52 final byte[] result = new byte[(int) file.length()];
53 final FileInputStream fileInputStream = new FileInputStream(file);
54 fileInputStream.read(result);
55 fileInputStream.close();
59 public static String getFileContentsAsString(final File file)
60 throws FileNotFoundException, IOException {
62 return new String(getFileContents(file), "UTF-8");
63 } catch (final UnsupportedEncodingException exception) {
64 throw new RuntimeException(exception);
69 * Compares new file content with old file content. If content in equal,
70 * then leaves file as-is. If content differs, then overrides file with the
74 * file to potentially overwrite
77 * @return <code>true</code> if file was overwritten.
79 * @throws FileNotFoundException
80 * if file is not found.
82 * if error happens during file IO.
84 public static boolean overwriteFileIfContentDiffers(final File file,
85 final byte[] newContent) throws FileNotFoundException, IOException {
88 if (file.length() == newContent.length) {
90 final byte[] oldContent = getFileContents(file);
92 for (int i = 0; i < newContent.length; i++)
93 if (newContent[i] != oldContent[i])
94 break checkForEquality;
96 // new file content in identical to old content
101 // New content differs from existing. Overwrite file.
102 saveToFile(file, newContent);
106 public static void saveToFile(final File file, final byte[] content)
108 final FileOutputStream fos = new FileOutputStream(file);