1. Project Clover database Mon Dec 22 2025 14:59:38 CST
  2. Package org.europa.together.utils

File FileUtils.java

 

Coverage histogram

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

Code metrics

24
95
11
1
293
185
33
0.35
8.64
11
3

Classes

Class Line # Actions
FileUtils 32 95 0% 33 8
0.9384615493.8%
 

Contributing tests

This file is covered by 49 tests. .

Source view

1    package org.europa.together.utils;
2   
3    import java.io.BufferedReader;
4    import java.io.BufferedWriter;
5    import java.io.ByteArrayOutputStream;
6    import java.io.File;
7    import java.io.FileInputStream;
8    import java.io.FileNotFoundException;
9    import java.io.FileOutputStream;
10    import java.io.IOException;
11    import java.io.InputStream;
12    import java.io.InputStreamReader;
13    import java.io.OutputStream;
14    import java.net.MalformedURLException;
15    import java.net.URL;
16    import java.nio.charset.Charset;
17    import java.nio.file.Files;
18    import java.nio.file.Paths;
19    import java.nio.file.StandardOpenOption;
20    import java.util.HashSet;
21    import java.util.Set;
22    import org.europa.together.application.LogbackLogger;
23    import org.europa.together.business.Logger;
24    import org.europa.together.domain.ByteOrderMark;
25    import org.europa.together.domain.LogLevel;
26    import org.springframework.context.ApplicationContext;
27    import org.springframework.context.support.ClassPathXmlApplicationContext;
28   
29    /**
30    * Some helpful stuff for file handling.
31    */
 
32    public final class FileUtils {
33   
34    private static final Logger LOGGER = new LogbackLogger(FileUtils.class);
35    private static final Charset CHARSET = Charset.forName("UTF-8");
36   
37    /**
38    * Constructor.
39    */
 
40  1 toggle private FileUtils() {
41  1 throw new UnsupportedOperationException();
42    }
43   
44    /**
45    * Convert an InputStream to an ByteArray.
46    *
47    * @param input as InputStream
48    * @return byte[] as Array
49    * @throws java.io.IOException case of error
50    */
 
51  2 toggle public static byte[] inputStreamToByteArray(final InputStream input)
52    throws IOException {
53  2 byte[] byteArray = null;
54  2 byteArray = input.readAllBytes();
55  1 return byteArray;
56    }
57   
58    /**
59    * Create from an HEX repersentation integers aa byte array.
60    *
61    * @param ints as Hex
62    * @return byte as Array
63    */
 
64  1 toggle public static byte[] toBytes(final int... ints) {
65  1 byte[] result = new byte[ints.length];
66  70 for (int i = 0; i < ints.length; i++) {
67  69 result[i] = (byte) ints[i];
68    }
69  1 return result;
70    }
71   
72    /**
73    * Write a String to a File.It is possible to create an empty file whitout
74    * content. DestinationFile is a full qualitied path including the file
75    * name. Sample: /home/user/file.txt
76    *
77    * @param content as String
78    * @param destinationFile as String
79    * @return true on success
80    * @throws java.io.IOException case of error
81    */
 
82  7 toggle public static boolean writeStringToFile(final String content, final String destinationFile)
83    throws IOException {
84  7 boolean success = false;
85  7 LOGGER.log("writeStringToFile() destination: " + destinationFile, LogLevel.DEBUG);
86  7 BufferedWriter writer
87    = Files.newBufferedWriter(Paths.get(destinationFile), CHARSET);
88  5 if (StringUtils.isEmpty(content)) {
89  1 LOGGER.log("File content is empty.", LogLevel.WARN);
90    } else {
91  4 LOGGER.log("Count of characters:"
92    + content.length(), LogLevel.DEBUG);
93  4 writer.append(content, 0, content.length());
94    }
95  5 writer.close();
96  5 success = true;
97  5 return success;
98    }
99   
100    /**
101    * Get the bytes of file. It is also possible to choose a dimension for the
102    * file size. The following options for <b>dimension</b> are available:
103    * kilo, mega, giga and tera.
104    *
105    * @param filePath as String
106    * @param dimension as String
107    * @return fileSize as double
108    */
 
109  10 toggle public static long getFileSize(final String filePath, final String dimension) {
110  10 String mode = "default";
111  10 if (!StringUtils.isEmpty(dimension)) {
112  5 mode = dimension;
113    }
114  10 File file = new File(filePath);
115  10 long size = 0;
116  10 if (file.exists()) {
117  9 size = file.length();
118  9 switch (mode) {
119  5 default:
120  5 break;
121  1 case "kilo":
122  1 size = size / Constraints.INT_1024;
123  1 break;
124  1 case "mega":
125  1 size = (size / Constraints.INT_1024) / Constraints.INT_1024;
126  1 break;
127  1 case "giga":
128  1 size = ((size / Constraints.INT_1024) / Constraints.INT_1024)
129    / Constraints.INT_1024;
130  1 break;
131  1 case "tera":
132  1 size = (((size / Constraints.INT_1024) / Constraints.INT_1024)
133    / Constraints.INT_1024) / Constraints.INT_1024;
134  1 break;
135    }
136  9 LOGGER.log("Size of " + file.getName() + " is " + size + " "
137    + mode + " Bytes.", LogLevel.DEBUG);
138    } else {
139  1 LOGGER.log("File " + filePath + " does not exists!", LogLevel.ERROR);
140    }
141  10 return size;
142    }
143   
144    /**
145    * Read a file from the class path.
146    *
147    * @param path to the file
148    * @return fielContent as String
149    * @throws FileNotFoundException case of error
150    */
 
151  1 toggle public static String readFileFromClasspath(final String path)
152    throws IOException {
153   
154  1 StringBuilder content = new StringBuilder();
155  1 ApplicationContext context = new ClassPathXmlApplicationContext();
156  1 BufferedReader reader = new BufferedReader(
157    new InputStreamReader(
158    context.getResource(path).getInputStream(), "UTF8")
159    );
160  1 String line;
161  ? while ((line = reader.readLine()) != null) {
162  1 content.append(line + " \n");
163    }
164  1 reader.close();
165  1 return content.toString();
166    }
167   
168    /**
169    * Read a binary remote resource like Image or PDF from a remote source
170    * (http / https) as a File object.
171    *
172    * @param uri as String
173    * @return resource as File
174    * @throws java.net.MalformedURLException case of error
175    */
 
176  2 toggle public static byte[] readRemoteResource(final URL uri)
177    throws MalformedURLException, IOException {
178  2 try {
179  2 InputStream inputStream = uri.openStream();
180   
181  1 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
182  1 byte[] buffer = new byte[Constraints.INT_1024];
183   
184  1 int numRead;
185  ? while ((numRead = inputStream.read(buffer)) != -1) {
186  1 outputStream.write(buffer, 0, numRead);
187    }
188  1 outputStream.close();
189  1 inputStream.close();
190   
191  1 return outputStream.toByteArray();
192   
193    } catch (Exception ex) {
194  1 throw new RuntimeException(ex);
195    }
196    }
197   
198    /**
199    * Reads the full content of a text file in UTF-8.The second parameter
200    * charset is optional.
201    *
202    * @param file as File
203    * @param charset as ByteOrderMark (Optional)
204    * @return fileContent as String
205    * @throws java.io.FileNotFoundException case of error
206    * @throws java.io.IOException case of error
207    */
 
208  36 toggle public static String readFileStream(final File file, final ByteOrderMark... charset)
209    throws FileNotFoundException, IOException {
210  36 StringBuilder content = new StringBuilder();
211  36 InputStreamReader inputStreamReader = null;
212  36 Charset encoding = CHARSET;
213  36 if (charset.length > 0) {
214  7 String encodingName = charset[0].toString();
215  7 if (encodingName.equals("NONE")) {
216  1 LOGGER.log("ByteOrderMark.NONE converted to UTF-8.", LogLevel.DEBUG);
217    } else {
218  6 encoding = Charset.forName(encodingName);
219    }
220    }
221  36 LOGGER.log("String encoded as " + encoding.displayName(), LogLevel.DEBUG);
222   
223  36 inputStreamReader = new InputStreamReader(new FileInputStream(file), encoding);
224  33 int line;
225  ? while ((line = inputStreamReader.read()) != -1) {
226  16202 content.append((char) line);
227    }
228  33 inputStreamReader.close();
229  33 return content.toString();
230    }
231   
232    /**
233    * Append content to a given text file at the end of the file in UTF-8.
234    *
235    * @param filePath as String
236    * @param content as String
237    * @throws java.io.IOException case of error
238    */
 
239  2 toggle public static void appendFile(final String filePath, final String content)
240    throws IOException {
241  2 Files.write(Paths.get(filePath), content.getBytes(CHARSET), StandardOpenOption.APPEND);
242  1 LOGGER.log(filePath + " extended with " + content.length() + " characters",
243    LogLevel.DEBUG);
244    }
245   
246    /**
247    * Copy a single File from a source to a destination.
248    *
249    * @param source as File
250    * @param destination as File
251    * @throws java.io.FileNotFoundException case of error
252    * @throws java.io.IOException case of error
253    */
 
254  4 toggle public static void copyFile(final File source, final File destination)
255    throws FileNotFoundException, IOException {
256  4 OutputStream os;
257  4 try (InputStream is = new FileInputStream(source)) {
258  3 os = new FileOutputStream(destination);
259  3 byte[] buffer = new byte[Constraints.INT_1024];
260  3 int length;
261  ? while ((length = is.read(buffer)) > 0) {
262  9 os.write(buffer, 0, length);
263    }
264    }
265  3 os.close();
266    }
267   
268    /**
269    * Discover a directory and all subdirectories to collect their the files in
270    * a List. The list entries are the full path, the filename with file
271    * extension. Empty directories will not listed. <br>
272    * Example /usr/home/john/file.txt
273    *
274    * @param directory as File
275    * @return a Set of Files
276    */
 
277  8 toggle public static Set<File> listFileTree(final File directory) {
278  8 Set<File> fileTree = new HashSet<>();
279  8 if (directory != null && directory.exists()
280    && directory.isDirectory()
281    && directory.listFiles().length != 0) {
282  4 for (File entry : directory.listFiles()) {
283  6 if (entry.isFile()) {
284  3 fileTree.add(entry);
285    } else {
286  3 fileTree.addAll(listFileTree(entry));
287    }
288    }
289    }
290  8 return fileTree;
291    }
292   
293    }