1. Project Clover database Wed Jan 17 2024 23:40:18 CST
  2. Package org.europa.together.utils

File FileUtils.java

 

Coverage histogram

../../../../img/srcFileCovDistChart10.png
0% of files have more coverage

Code metrics

18
71
8
1
216
138
23
0.32
8.88
8
2.88

Classes

Class Line # Actions
FileUtils 26 71 0% 23 4
0.958762995.9%
 

Contributing tests

This file is covered by 45 tests. .

Source view

1    package org.europa.together.utils;
2   
3    import java.io.BufferedWriter;
4    import java.io.File;
5    import java.io.FileInputStream;
6    import java.io.FileNotFoundException;
7    import java.io.FileOutputStream;
8    import java.io.IOException;
9    import java.io.InputStream;
10    import java.io.InputStreamReader;
11    import java.io.OutputStream;
12    import java.nio.charset.Charset;
13    import java.nio.file.Files;
14    import java.nio.file.Paths;
15    import java.nio.file.StandardOpenOption;
16    import java.util.HashSet;
17    import java.util.Set;
18    import org.europa.together.application.LogbackLogger;
19    import org.europa.together.business.Logger;
20    import org.europa.together.domain.ByteOrderMark;
21    import org.europa.together.domain.LogLevel;
22   
23    /**
24    * Some helpful stuff for file handling.
25    */
 
26    public final class FileUtils {
27   
28    private static final Logger LOGGER = new LogbackLogger(FileUtils.class);
29    private static final Charset CHARSET = Charset.forName("UTF-8");
30    private static final int BYTES = 1024;
31   
32    /**
33    * Constructor.
34    */
 
35  1 toggle private FileUtils() {
36  1 throw new UnsupportedOperationException();
37    }
38   
39    /**
40    * Convert an InputStream to an ByteArray.
41    *
42    * @param input as InputStream
43    * @return byte[] as Array
44    * @throws java.io.IOException
45    */
 
46  2 toggle public static byte[] inputStreamToByteArray(final InputStream input)
47    throws IOException {
48  2 byte[] byteArray = {};
49  2 byteArray = input.readAllBytes();
50  1 return byteArray;
51    }
52   
53    /**
54    * Write a String to a File.It is possible to create an empty file whitout
55    * content. DestinationFile is a full qualitied path including the file
56    * name. Sample: /home/user/file.txt
57    *
58    * @param content as String
59    * @param destinationFile as String
60    * @return true on success
61    * @throws java.io.IOException
62    */
 
63  7 toggle public static boolean writeStringToFile(final String content, final String destinationFile)
64    throws IOException {
65  7 boolean success = false;
66  7 LOGGER.log("writeStringToFile() destination: " + destinationFile, LogLevel.DEBUG);
67  7 BufferedWriter writer
68    = Files.newBufferedWriter(Paths.get(destinationFile), CHARSET);
69  5 if (StringUtils.isEmpty(content)) {
70  1 LOGGER.log("File content is empty.", LogLevel.WARN);
71    } else {
72  4 LOGGER.log("Count of characters:"
73    + content.length(), LogLevel.DEBUG);
74  4 writer.append(content, 0, content.length());
75    }
76  5 writer.close();
77  5 success = true;
78  5 return success;
79    }
80   
81    /**
82    * Get the bytes of file. It is also possible to choose a dimension for the
83    * file size. The following options for <b>dimension</b> are available:
84    * kilo, mega, giga and tera.
85    *
86    * @param filePath as String
87    * @param dimension as String
88    * @return fileSize as double
89    */
 
90  10 toggle public static long getFileSize(final String filePath, final String dimension) {
91  10 String mode = "default";
92  10 if (!StringUtils.isEmpty(dimension)) {
93  5 mode = dimension;
94    }
95  10 File file = new File(filePath);
96  10 long size = 0;
97  10 if (file.exists()) {
98  9 size = file.length();
99  9 switch (mode) {
100  5 default:
101  5 break;
102  1 case "kilo":
103  1 size = size / Constraints.INT_1024;
104  1 break;
105  1 case "mega":
106  1 size = (size / Constraints.INT_1024) / Constraints.INT_1024;
107  1 break;
108  1 case "giga":
109  1 size = ((size / Constraints.INT_1024) / Constraints.INT_1024)
110    / Constraints.INT_1024;
111  1 break;
112  1 case "tera":
113  1 size = (((size / Constraints.INT_1024) / Constraints.INT_1024)
114    / Constraints.INT_1024) / Constraints.INT_1024;
115  1 break;
116    }
117  9 LOGGER.log("Size of " + file.getName() + " is " + size + " "
118    + mode + " Bytes.", LogLevel.DEBUG);
119    } else {
120  1 LOGGER.log("File " + filePath + " does not exists!", LogLevel.ERROR);
121    }
122  10 return size;
123    }
124   
125    /**
126    * Reads the full content of a text file in UTF-8.The second parameter
127    * charset is optional.
128    *
129    * @param file as File
130    * @param charset as ByteOrderMark (Optional)
131    * @return fileContent as String
132    * @throws java.io.FileNotFoundException
133    * @throws java.io.IOException
134    */
 
135  36 toggle public static String readFileStream(final File file, final ByteOrderMark... charset)
136    throws FileNotFoundException, IOException {
137  36 StringBuilder content = new StringBuilder();
138  36 InputStreamReader inputStreamReader = null;
139  36 Charset encoding = CHARSET;
140  36 if (charset.length > 0) {
141  8 String encodingName = charset[0].toString();
142  8 if (encodingName.equals("NONE")) {
143  1 LOGGER.log("ByteOrderMark.NONE converted to UTF-8.", LogLevel.DEBUG);
144    } else {
145  7 encoding = Charset.forName(encodingName);
146    }
147    }
148  36 LOGGER.log("String encoded as " + encoding.displayName(), LogLevel.DEBUG);
149   
150  36 inputStreamReader = new InputStreamReader(new FileInputStream(file), encoding);
151  34 int line;
152  ? while ((line = inputStreamReader.read()) != -1) {
153  16234 content.append((char) line);
154    }
155  34 inputStreamReader.close();
156  34 return content.toString();
157    }
158   
159    /**
160    * Append content to a given text file at the end of the file in UTF-8.
161    *
162    * @param filePath as String
163    * @param content as String
164    * @throws java.io.IOException
165    */
 
166  2 toggle public static void appendFile(final String filePath, final String content)
167    throws IOException {
168  2 Files.write(Paths.get(filePath), content.getBytes(CHARSET), StandardOpenOption.APPEND);
169  1 LOGGER.log(filePath + " extended with " + content.length() + " characters",
170    LogLevel.DEBUG);
171    }
172   
173    /**
174    * Copy a single File from a source to a destination.
175    *
176    * @param source as File
177    * @param destination as File
178    * @throws java.io.FileNotFoundException
179    * @throws java.io.IOException
180    */
 
181  4 toggle public static void copyFile(final File source, final File destination)
182    throws FileNotFoundException, IOException {
183  4 InputStream is = new FileInputStream(source);
184  3 OutputStream os = new FileOutputStream(destination);
185  3 byte[] buffer = new byte[BYTES];
186  3 int length;
187  ? while ((length = is.read(buffer)) > 0) {
188  14 os.write(buffer, 0, length);
189    }
190  3 is.close();
191  3 os.close();
192    }
193   
194    /**
195    * Discover a directory and all subdirectories to collect their the files in
196    * a List. The list entries are the full path, the filename with file
197    * extension. Empty directories will not listed. <br>
198    * Example /usr/home/john/file.txt
199    *
200    * @param directory as File
201    * @return a Set of Files
202    */
 
203  7 toggle public static Set<File> listFileTree(final File directory) {
204  7 Set<File> fileTree = new HashSet<>();
205  7 if (directory != null && directory.isDirectory() && directory.listFiles().length != 0) {
206  4 for (File entry : directory.listFiles()) {
207  6 if (entry.isFile()) {
208  3 fileTree.add(entry);
209    } else {
210  3 fileTree.addAll(listFileTree(entry));
211    }
212    }
213    }
214  7 return fileTree;
215    }
216    }