initial commit
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / file / IOHelper.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright (C) 2012, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  * 
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.
8  */
9
10 package eu.svjatoslav.commons.file;
11
12 import java.io.File;
13 import java.io.FileInputStream;
14 import java.io.FileNotFoundException;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17
18 public class IOHelper {
19
20         public static byte[] getFileContents(final File file)
21                         throws FileNotFoundException, IOException {
22
23                 final byte[] result = new byte[(int) file.length()];
24                 final FileInputStream fileInputStream = new FileInputStream(file);
25                 fileInputStream.read(result);
26                 fileInputStream.close();
27                 return result;
28         }
29
30         /**
31          * Compares new file content with old file content. If content in equal,
32          * then leaves file as-is. If content differs, then overrides file with the
33          * new content.
34          * 
35          * @return <code>true</code> if file was overwritten.
36          */
37         public static boolean overwriteFileIfContentDiffers(final File file,
38                         final byte[] newContent) throws FileNotFoundException, IOException {
39
40                 checkForEquality: {
41                         if (file.length() == newContent.length) {
42
43                                 final byte[] oldContent = getFileContents(file);
44
45                                 for (int i = 0; i < newContent.length; i++)
46                                         if (newContent[i] != oldContent[i])
47                                                 break checkForEquality;
48
49                                 // new file content in identical to old content
50                                 return false;
51                         }
52                 }
53
54                 // New content differs from existing. Overwrite file.
55                 saveToFile(file, newContent);
56                 return true;
57         }
58
59         public static void saveToFile(final File file, final byte[] content)
60                         throws IOException {
61                 final FileOutputStream fos = new FileOutputStream(file);
62                 fos.write(content);
63                 fos.close();
64         }
65
66 }