1 package org.eparapher.core.tools;
2
3
4 import java.io.BufferedOutputStream;
5 import java.io.DataInputStream;
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12
13
14
15
16
17
18
19
20 public class FileUtil {
21
22
23
24
25
26
27
28 public static void writeToFile(String fileName, InputStream iStream)
29 throws IOException
30 {
31 writeToFile(fileName, iStream, false);
32 }
33
34
35
36
37
38
39
40
41
42
43
44
45
46 public static void writeToFile(String fileName, InputStream iStream,
47 boolean createDir)
48 throws IOException
49 {
50 String me = "FileUtil.WriteToFile";
51 if (fileName == null)
52 {
53 throw new IOException(me + ": filename is null");
54 }
55 if (iStream == null)
56 {
57 throw new IOException(me + ": InputStream is null");
58 }
59
60 File theFile = new File(fileName);
61
62
63 if (theFile.exists())
64 {
65 String msg =
66 theFile.isDirectory() ? "directory" :
67 (! theFile.canWrite() ? "not writable" : null);
68 if (msg != null)
69 {
70 throw new IOException(me + ": file '" + fileName + "' is " + msg);
71 }
72 }
73
74
75 if (createDir && theFile.getParentFile() != null)
76 {
77 theFile.getParentFile().mkdirs();
78 }
79
80
81 BufferedOutputStream fOut = null;
82 try
83 {
84 fOut = new BufferedOutputStream(new FileOutputStream(theFile));
85 byte[] buffer = new byte[32 * 1024];
86 int bytesRead = 0;
87 while ((bytesRead = iStream.read(buffer)) != -1)
88 {
89 fOut.write(buffer, 0, bytesRead);
90 }
91 }
92 catch (Exception e)
93 {
94 throw new IOException(me + " failed, got: " + e.toString());
95 }
96 finally
97 {
98 close(iStream, fOut);
99 }
100 }
101
102 public static void writeToFile(String fileName, byte[] data)
103 throws IOException {
104 FileOutputStream envfos = new FileOutputStream(fileName);
105 envfos.write(data);
106 envfos.close();
107 }
108
109
110
111
112
113
114
115
116 protected static void close(InputStream iStream, OutputStream oStream)
117 throws IOException
118 {
119 try
120 {
121 if (iStream != null)
122 {
123 iStream.close();
124 }
125 }
126 finally
127 {
128 if (oStream != null)
129 {
130 oStream.close();
131 }
132 }
133 }
134
135
136 public static boolean fileExists(String fileName) {
137 File file = new File(fileName);
138 return file.exists();
139 }
140
141 public static boolean fileEmpty(String fileName) {
142 File file = new File(fileName);
143 long filesize = file.length();
144 return (file.length() == 0L);
145 }
146
147 public static byte[] readFile(String fileName) throws IOException {
148
149 File file_to_sign = new File(fileName);
150 byte[] buffer = new byte[(int)file_to_sign.length()];
151 DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
152 in.readFully(buffer);
153 in.close();
154
155 return buffer;
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183 }
184
185
186
187 }