2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2013, 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 2 of the GNU General Public License
7 * 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;
18 public class IOHelper {
21 * Deletes files and directories recursively. WARNING!!! Follows symlinks!!!
23 public static void deleteRecursively(final File file) throws IOException {
24 if (file.isDirectory()) {
26 for (final File subFile : file.listFiles())
27 deleteRecursively(subFile);
30 throw new FileNotFoundException("Failed to delete directory: "
38 throw new FileNotFoundException("Failed to delete file: "
42 public static byte[] getFileContents(final File file)
43 throws FileNotFoundException, IOException {
45 final byte[] result = new byte[(int) file.length()];
46 final FileInputStream fileInputStream = new FileInputStream(file);
47 fileInputStream.read(result);
48 fileInputStream.close();
53 * Compares new file content with old file content. If content in equal,
54 * then leaves file as-is. If content differs, then overrides file with the
57 * @return <code>true</code> if file was overwritten.
59 public static boolean overwriteFileIfContentDiffers(final File file,
60 final byte[] newContent) throws FileNotFoundException, IOException {
63 if (file.length() == newContent.length) {
65 final byte[] oldContent = getFileContents(file);
67 for (int i = 0; i < newContent.length; i++)
68 if (newContent[i] != oldContent[i])
69 break checkForEquality;
71 // new file content in identical to old content
76 // New content differs from existing. Overwrite file.
77 saveToFile(file, newContent);
81 public static void saveToFile(final File file, final byte[] content)
83 final FileOutputStream fos = new FileOutputStream(file);