1 package ca.uhn.hl7v2.hoh.util;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.File;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.util.List;
9
10
11
12
13 public class IOUtils {
14
15 public static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
16 public static final String FILE_PATH_SEP = System.getProperty("file.separator");
17
18 private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(IOUtils.class);
19
20
21
22
23 private IOUtils() {
24 super();
25 }
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 public static long copy(InputStream input, OutputStream output) throws IOException {
47 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
48 long count = 0;
49 int n;
50 while (-1 != (n = input.read(buffer))) {
51 output.write(buffer, 0, n);
52 count += n;
53 }
54 return count;
55 }
56
57 public static long copyWhileDataAvailable(InputStream input, OutputStream output) throws IOException {
58 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
59 long count = 0;
60 int n;
61 while (input.available() > 0 && -1 != (n = input.read(buffer))) {
62 output.write(buffer, 0, n);
63 count += n;
64 }
65 return count;
66 }
67
68 public static void deleteAllFromDirectory(File theWorkfilesDir) {
69 File[] listFiles = theWorkfilesDir.listFiles();
70 if (listFiles.length == 0) {
71 return;
72 }
73 ourLog.info("Deleting {} files from {}", listFiles.length, theWorkfilesDir.getAbsoluteFile());
74 for (File next : listFiles) {
75 ourLog.info("Deleting existing file: " + next);
76 next.delete();
77 }
78 }
79
80 public static void deleteAllFromDirectoryExcept(File theDirectory, List<File> theExcept) throws IOException {
81 File[] listFiles = theDirectory.listFiles();
82 if (listFiles.length == 0) {
83 return;
84 }
85 ourLog.info("Deleting unneeded files from {}", theDirectory.getAbsoluteFile());
86 for (File nextFile : listFiles) {
87 boolean keep = false;
88 for (File nextExcept : theExcept) {
89 if (nextFile.getCanonicalPath().equals(nextExcept.getCanonicalPath())) {
90 keep = true;
91 break;
92 }
93 }
94 if (!keep) {
95 ourLog.info("Deleting existing file: " + nextFile);
96 nextFile.delete();
97 }
98 }
99 }
100
101
102
103
104 public static byte[] readClasspathIntoByteArray(String theString) throws IOException {
105 InputStream res = IOUtils.class.getResourceAsStream(theString);
106 return readInputStreamIntoByteArray(res);
107 }
108
109 public static byte[] readInputStreamIntoByteArraWhileDataAvailable(InputStream res) throws IOException {
110 java.io.ByteArrayOutputStream bos = new ByteArrayOutputStream();
111 copyWhileDataAvailable(res, bos);
112 return bos.toByteArray();
113 }
114
115
116
117
118 public static byte[] readInputStreamIntoByteArray(InputStream res) throws IOException {
119 java.io.ByteArrayOutputStream bos = new ByteArrayOutputStream();
120 copy(res, bos);
121 return bos.toByteArray();
122 }
123
124 }