标签:
功能:文件夹创建、文件删除、文件保存和读取、文件压缩与解压缩、excel文件打印
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Reader; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.text.DecimalFormat; import java.util.Enumeration; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import jp.ne.so_net.ga2.no_ji.jcom.ReleaseManager; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelApplication; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbook; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorkbooks; import jp.ne.so_net.ga2.no_ji.jcom.excel8.ExcelWorksheet; import org.apache.commons.io.FileUtils; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; /** * 常用文件(夹)处理方法工具类 */ public class FileUtil { /** * 创建文件夹 * @param path 文件夹路径 */ public static void mkdirs(String path){ File folder = new File(path); if(!folder.exists()){ folder.mkdirs(); } } /** * 删除文件夹下的所有文件 * @param rootPath 文件夹路径 * @return 删除是否成功 */ public static boolean deleteAll(String rootPath){ try { File f = new File(rootPath); String[] files = f.list(); //判断文件夹是否存在文件 if(files != null && files.length != 0){ for(int i = 0; i < files.length; i++) { File file = new File(rootPath + files[i]); if(file.exists()) FileUtils.forceDelete(file); } } return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * 删除单个文件 * @param fileName 要删除的文件的文件名 * @return 删除是否成功 */ public static boolean deleteFile(String fileName) { File file = new File(fileName); // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除 if (file.exists() && file.isFile()) { if (file.delete()) { return true; } else { return false; } } else { return false; } } /** * 保存输入流中的文件 * @param inputStream 输入流 * @param outFilePath 保存的文件路径 * @return 保存是否成功 */ public static boolean saveFileFromInputStream(InputStream inputStream,String outFilePath) { try{ FileOutputStream fileOutputStream = new FileOutputStream(outFilePath); byte[] buffer =new byte[1024*1024]; int byteread = 0; while ((byteread=inputStream.read(buffer))!=-1) { fileOutputStream.write(buffer,0,byteread); fileOutputStream.flush(); } fileOutputStream.close(); inputStream.close(); return true; }catch(Exception e){ return false; } } /** * 以行为单位读取文件,常用于读面向行的格式化文件 * @param fileName 文件的路径 * @return */ public static String readFileByLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; StringBuffer buf = new StringBuffer(); try { reader = new BufferedReader(new FileReader(file)); String tempString = null; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 buf.append(tempString+"</br>"); } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } return buf.toString(); } /** * 以字符为单位读取文件,常用于读文本,数字等类型的文件 * @param fileName 文件的路径 * @return */ public static String readFileByChars(String fileName) { File file = new File(fileName); Reader reader = null; StringBuffer buf = new StringBuffer(); try { // 一次读一个字符 reader = new InputStreamReader(new FileInputStream(file)); int tempchar; while ((tempchar = reader.read()) != -1) { // 对于windows下,\r\n这两个字符在一起时,表示一个换行。 // 但如果这两个字符分开显示时,会换两次行。 // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。 if (((char) tempchar) != ‘\r‘) { buf.append((char) tempchar); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } return buf.toString(); } /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 * MappedByteBuffer 可以在处理大文件时,提升性能 * @param fileName 文件的路径 * @return */ public static byte[] readFileByBytes(String fileName) { FileChannel fc = null; byte[] result = null; try{ fc = new RandomAccessFile(fileName,"r").getChannel(); MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load(); result = new byte[(int)fc.size()]; if (byteBuffer.remaining() > 0) { byteBuffer.get(result, 0, byteBuffer.remaining()); } }catch (IOException e) { e.printStackTrace(); }finally{ try{ fc.close(); }catch (IOException e) { e.printStackTrace(); } } return result; } /** * 读取properties配置文件 * @param filePath 文件路径 * @return */ public static Properties loadProperty(String filePath) { Properties prop=new Properties(); try { File file = new File(filePath); prop.load(new FileReader(file.getAbsolutePath())); }catch (IOException e) { e.printStackTrace(); } return prop; } /** * 转换文件大小 * @param fileS 文件长度,单位byte * @return 单位B、K、M、G */ public static String FormetFileSize(long fileS) { DecimalFormat df = new DecimalFormat("#.00"); String fileSizeString = ""; if (fileS < 1024) { fileSizeString = df.format((double) fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.format((double) fileS / 1024) + "K"; } else if (fileS < 1073741824) { fileSizeString = df.format((double) fileS / 1048576) + "M"; } else { fileSizeString = df.format((double) fileS / 1073741824) + "G"; } return fileSizeString; } /** * 压缩多个文件成一个zip文件 * @param srcfile 源文件列表 * @param zipfile 压缩后的文件 * @return 压缩是否成功 */ public static boolean zip(File[] srcfile, File zipfile) { byte[] buf = new byte[1024]; try { // ZipOutputStream类:完成文件或文件夹的压缩 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < srcfile.length; i++) { FileInputStream in = new FileInputStream(srcfile[i]); out.putNextEntry(new ZipEntry(srcfile[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); return true; } catch (Exception e) { return false; } } /** * 解压缩zip文件 * @param zipfile 需要解压缩的文件 * @param descDir 解压后的目标目录 * @return 解压是否成功 */ public static boolean unZip(File zipfile, String descDir) { try { ZipFile zf = new ZipFile(zipfile); for (Enumeration entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); String zipEntryName = entry.getName(); InputStream in = zf.getInputStream(entry); OutputStream out = new FileOutputStream(descDir + zipEntryName); byte[] buf1 = new byte[1024]; int len; while ((len = in.read(buf1)) > 0) { out.write(buf1, 0, len); } in.close(); out.close(); } return true; } catch (Exception e) { return false; } } /** * 通过jcom后台打印excel文件,需要服务以进程方式启动 * @param fname 文件路径 * @return 打印是否成功 */ public static boolean printExcel4Jcom(String fname){ ReleaseManager rm = new ReleaseManager(); try{ ExcelApplication excel = new ExcelApplication(rm); ExcelWorkbooks xlBooks = excel.Workbooks(); ExcelWorkbook xlBook = xlBooks.Open(fname); ExcelWorksheet xlSheet = excel.ActiveSheet(); xlSheet.PrintOut(); xlBook.Close(false, null, false); excel.Quit(); }catch(Exception e){ e.printStackTrace(); return false; }finally{ rm.release(); } return true; } /** * 通过jacob后台打印excel文件,需要服务以进程方式启动 * @param path Excel文件路径 * @return 打印是否成功 */ public static boolean printExcel4Jacob(String path){ ComThread.InitSTA(); ActiveXComponent xl = new ActiveXComponent("Excel.Application"); try { // 不打开文档 // Dispatch.put(xl, "Visible", new Variant(false)); Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); Dispatch workbook = Dispatch.call(workbooks, "Open", path).toDispatch(); // 开始打印 // Dispatch.get(workbook, "PrintOut"); Dispatch.callN(workbook, "PrintOut", new Object[] { Variant.VT_MISSING, Variant.VT_MISSING, new Integer(1), new Boolean(false), null, new Boolean(true), Variant.VT_MISSING, "" }); Dispatch.call(workbook, "Close"); System.out.println("打印执行成功"); } catch (Exception e) { System.out.println("JACOB打印失败"+e); return false; } finally { // 始终释放资源 xl.invoke("Quit", new Variant[] {}); ComThread.Release(); } return true; } /** * 文件属性类 */ public static class FileProperties{ private String id; /** * 文件大小 */ private String fileSize; /** * 文件名称 */ private String fileName; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } } }
标签:
原文地址:http://www.cnblogs.com/Mr-kevin/p/5559033.html