常用文件(夾)處理方法工具類,處理方法工具類
功能:文件夾創建、文件刪除、文件保存和讀取、文件壓縮與解壓縮、excel文件打印

![]()
1 import java.io.BufferedReader;
2 import java.io.File;
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.io.OutputStream;
10 import java.io.RandomAccessFile;
11 import java.io.Reader;
12 import java.nio.MappedByteBuffer;
13 import java.nio.channels.FileChannel;
14 import java.nio.channels.FileChannel.MapMode;
15 import java.text.DecimalFormat;
16 import java.util.Enumeration;
17 import java.util.Properties;
18 import java.util.zip.ZipEntry;
19 import java.util.zip.ZipFile;
20 import java.util.zip.ZipOutputStream;
21
22 import jp.ne.so_net.ga2.no_ji.jcom.ReleaseManager;
23 import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelApplication;
24 import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbook;
25 import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbooks;
26 import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorksheet;
27
28 import org.apache.commons.io.FileUtils;
29
30 import com.jacob.activeX.ActiveXComponent;
31 import com.jacob.com.ComThread;
32 import com.jacob.com.Dispatch;
33 import com.jacob.com.Variant;
34
35 /**
36 * 常用文件(夾)處理方法工具類
37 */
38 public class FileUtil {
39
40 /**
41 * 創建文件夾
42 * @param path 文件夾路徑
43 */
44 public static void mkdirs(String path){
45 File folder = new File(path);
46 if(!folder.exists()){
47 folder.mkdirs();
48 }
49 }
50
51 /**
52 * 刪除文件夾下的所有文件
53 * @param rootPath 文件夾路徑
54 * @return 刪除是否成功
55 */
56 public static boolean deleteAll(String rootPath){
57 try {
58 File f = new File(rootPath);
59 String[] files = f.list();
60 //判斷文件夾是否存在文件
61 if(files != null && files.length != 0){
62 for(int i = 0; i < files.length; i++) {
63 File file = new File(rootPath + files[i]);
64 if(file.exists())
65 FileUtils.forceDelete(file);
66 }
67 }
68 return true;
69 } catch (IOException e) {
70 e.printStackTrace();
71 return false;
72 }
73 }
74
75 /**
76 * 刪除單個文件
77 * @param fileName 要刪除的文件的文件名
78 * @return 刪除是否成功
79 */
80 public static boolean deleteFile(String fileName) {
81 File file = new File(fileName);
82 // 如果文件路徑所對應的文件存在,並且是一個文件,則直接刪除
83 if (file.exists() && file.isFile()) {
84 if (file.delete()) {
85 return true;
86 } else {
87 return false;
88 }
89 } else {
90 return false;
91 }
92 }
93
94 /**
95 * 保存輸入流中的文件
96 * @param inputStream 輸入流
97 * @param outFilePath 保存的文件路徑
98 * @return 保存是否成功
99 */
100 public static boolean saveFileFromInputStream(InputStream inputStream,String outFilePath) {
101 try{
102 FileOutputStream fileOutputStream = new FileOutputStream(outFilePath);
103 byte[] buffer =new byte[1024*1024];
104 int byteread = 0;
105 while ((byteread=inputStream.read(buffer))!=-1)
106 {
107 fileOutputStream.write(buffer,0,byteread);
108 fileOutputStream.flush();
109 }
110 fileOutputStream.close();
111 inputStream.close();
112 return true;
113 }catch(Exception e){
114 return false;
115 }
116 }
117
118 /**
119 * 以行為單位讀取文件,常用於讀面向行的格式化文件
120 * @param fileName 文件的路徑
121 * @return
122 */
123 public static String readFileByLines(String fileName) {
124 File file = new File(fileName);
125 BufferedReader reader = null;
126 StringBuffer buf = new StringBuffer();
127 try {
128 reader = new BufferedReader(new FileReader(file));
129 String tempString = null;
130 // 一次讀入一行,直到讀入null為文件結束
131 while ((tempString = reader.readLine()) != null) {
132 // 顯示行號
133 buf.append(tempString+"</br>");
134 }
135 reader.close();
136 } catch (IOException e) {
137 e.printStackTrace();
138 } finally {
139 if (reader != null) {
140 try {
141 reader.close();
142 } catch (IOException e1) {
143 }
144 }
145 }
146 return buf.toString();
147 }
148
149 /**
150 * 以字符為單位讀取文件,常用於讀文本,數字等類型的文件
151 * @param fileName 文件的路徑
152 * @return
153 */
154 public static String readFileByChars(String fileName) {
155 File file = new File(fileName);
156 Reader reader = null;
157 StringBuffer buf = new StringBuffer();
158 try {
159 // 一次讀一個字符
160 reader = new InputStreamReader(new FileInputStream(file));
161 int tempchar;
162 while ((tempchar = reader.read()) != -1) {
163 // 對於windows下,\r\n這兩個字符在一起時,表示一個換行。
164 // 但如果這兩個字符分開顯示時,會換兩次行。
165 // 因此,屏蔽掉\r,或者屏蔽\n。否則,將會多出很多空行。
166 if (((char) tempchar) != '\r') {
167 buf.append((char) tempchar);
168 }
169 }
170 reader.close();
171 } catch (Exception e) {
172 e.printStackTrace();
173 }
174 return buf.toString();
175 }
176
177 /**
178 * 以字節為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
179 * MappedByteBuffer 可以在處理大文件時,提升性能
180 * @param fileName 文件的路徑
181 * @return
182 */
183 public static byte[] readFileByBytes(String fileName) {
184 FileChannel fc = null;
185 byte[] result = null;
186 try{
187 fc = new RandomAccessFile(fileName,"r").getChannel();
188 MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();
189 result = new byte[(int)fc.size()];
190 if (byteBuffer.remaining() > 0) {
191 byteBuffer.get(result, 0, byteBuffer.remaining());
192 }
193 }catch (IOException e) {
194 e.printStackTrace();
195 }finally{
196 try{
197 fc.close();
198 }catch (IOException e) {
199 e.printStackTrace();
200 }
201 }
202 return result;
203 }
204
205 /**
206 * 讀取properties配置文件
207 * @param filePath 文件路徑
208 * @return
209 */
210 public static Properties loadProperty(String filePath) {
211 Properties prop=new Properties();
212 try {
213 File file = new File(filePath);
214 prop.load(new FileReader(file.getAbsolutePath()));
215 }catch (IOException e) {
216 e.printStackTrace();
217 }
218 return prop;
219 }
220
221 /**
222 * 轉換文件大小
223 * @param fileS 文件長度,單位byte
224 * @return 單位B、K、M、G
225 */
226 public static String FormetFileSize(long fileS) {
227 DecimalFormat df = new DecimalFormat("#.00");
228 String fileSizeString = "";
229 if (fileS < 1024) {
230 fileSizeString = df.format((double) fileS) + "B";
231 } else if (fileS < 1048576) {
232 fileSizeString = df.format((double) fileS / 1024) + "K";
233 } else if (fileS < 1073741824) {
234 fileSizeString = df.format((double) fileS / 1048576) + "M";
235 } else {
236 fileSizeString = df.format((double) fileS / 1073741824) + "G";
237 }
238 return fileSizeString;
239 }
240
241 /**
242 * 壓縮多個文件成一個zip文件
243 * @param srcfile 源文件列表
244 * @param zipfile 壓縮後的文件
245 * @return 壓縮是否成功
246 */
247 public static boolean zip(File[] srcfile, File zipfile) {
248 byte[] buf = new byte[1024];
249 try {
250 // ZipOutputStream類:完成文件或文件夾的壓縮
251 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
252 for (int i = 0; i < srcfile.length; i++) {
253 FileInputStream in = new FileInputStream(srcfile[i]);
254 out.putNextEntry(new ZipEntry(srcfile[i].getName()));
255 int len;
256 while ((len = in.read(buf)) > 0) {
257 out.write(buf, 0, len);
258 }
259 out.closeEntry();
260 in.close();
261 }
262 out.close();
263 return true;
264 } catch (Exception e) {
265 return false;
266 }
267 }
268
269 /**
270 * 解壓縮zip文件
271 * @param zipfile 需要解壓縮的文件
272 * @param descDir 解壓後的目標目錄
273 * @return 解壓是否成功
274 */
275 public static boolean unZip(File zipfile, String descDir) {
276 try {
277 ZipFile zf = new ZipFile(zipfile);
278 for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
279 ZipEntry entry = (ZipEntry) entries.nextElement();
280 String zipEntryName = entry.getName();
281 InputStream in = zf.getInputStream(entry);
282 OutputStream out = new FileOutputStream(descDir + zipEntryName);
283 byte[] buf1 = new byte[1024];
284 int len;
285 while ((len = in.read(buf1)) > 0) {
286 out.write(buf1, 0, len);
287 }
288 in.close();
289 out.close();
290 }
291 return true;
292 } catch (Exception e) {
293 return false;
294 }
295 }
296
297 /**
298 * 通過jcom後台打印excel文件,需要服務以進程方式啟動
299 * @param fname 文件路徑
300 * @return 打印是否成功
301 */
302 public static boolean printExcel4Jcom(String fname){
303 ReleaseManager rm = new ReleaseManager();
304 try{
305 ExcelApplication excel = new ExcelApplication(rm);
306 ExcelWorkbooks xlBooks = excel.Workbooks();
307 ExcelWorkbook xlBook = xlBooks.Open(fname);
308 ExcelWorksheet xlSheet = excel.ActiveSheet();
309 xlSheet.PrintOut();
310 xlBook.Close(false, null, false);
311 excel.Quit();
312 }catch(Exception e){
313 e.printStackTrace();
314 return false;
315 }finally{
316 rm.release();
317 }
318 return true;
319 }
320
321 /**
322 * 通過jacob後台打印excel文件,需要服務以進程方式啟動
323 * @param path Excel文件路徑
324 * @return 打印是否成功
325 */
326 public static boolean printExcel4Jacob(String path){
327 ComThread.InitSTA();
328 ActiveXComponent xl = new ActiveXComponent("Excel.Application");
329 try {
330 // 不打開文檔
331 // Dispatch.put(xl, "Visible", new Variant(false));
332 Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
333
334 Dispatch workbook = Dispatch.call(workbooks, "Open", path).toDispatch();
335 // 開始打印
336 // Dispatch.get(workbook, "PrintOut");
337 Dispatch.callN(workbook, "PrintOut", new Object[] { Variant.VT_MISSING, Variant.VT_MISSING, new Integer(1),
338 new Boolean(false), null, new Boolean(true), Variant.VT_MISSING, "" });
339 Dispatch.call(workbook, "Close");
340 System.out.println("打印執行成功");
341 } catch (Exception e) {
342 System.out.println("JACOB打印失敗"+e);
343 return false;
344 } finally {
345 // 始終釋放資源
346 xl.invoke("Quit", new Variant[] {});
347 ComThread.Release();
348 }
349 return true;
350 }
351
352 /**
353 * 文件屬性類
354 */
355 public static class FileProperties{
356
357 private String id;
358
359 /**
360 * 文件大小
361 */
362 private String fileSize;
363
364 /**
365 * 文件名稱
366 */
367 private String fileName;
368
369
370 public String getId() {
371 return id;
372 }
373 public void setId(String id) {
374 this.id = id;
375 }
376
377 public String getFileSize() {
378 return fileSize;
379 }
380 public void setFileSize(String fileSize) {
381 this.fileSize = fileSize;
382 }
383
384 public String getFileName() {
385 return fileName;
386 }
387 public void setFileName(String fileName) {
388 this.fileName = fileName;
389 }
390 }
391 }
View Code