常用文件(夹)处理方法工具类

此文章是基于  搭建Jquery+SpringMVC+Spring+Hibernate+MySQL平台

 

功能:文件夹创建、文件删除、文件保存和读取、文件压缩与解压缩、excel文件打印

 

一. jar包介绍 

  1. commons-io-2.5.jar

  2. jcom.jar,用于打印

  3. jacob.jar,用于打印

 

二. 类文件介绍

  FileUtil.java,文件(夹)处理工具类:  

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

 

posted on 2016-06-04 16:25  大饼酥  阅读(697)  评论(0编辑  收藏  举报

导航