文件操作(文件過濾,壓縮,導出到excel等)

文件過濾

通過實現文件名過濾器FilenameFilter,過濾指定的文件列表

//根據後綴名過濾文件列表
public class FolderFilter implements FilenameFilter {
    private String extensions; // 後綴名
    public FolderFilter(String extensions){
        this.extensions = extensions;
    }

    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(extensions);
    }
}

//根據文件名過濾文件列表
public static class ContainFolderFilter implements FilenameFilter {

    private String extensions; // 後綴名

    public ContainFolderFilter(String extensions){
        this.extensions = extensions;
    }

    @Override
    public boolean accept(File dir, String name) {
        return -1!=name.indexOf(extensions);
    }
}

/**
 * 查找文件列表
 */
public String[] getFileList(String dirPath,String extensions){
    File  file = new File(dirPath);
    String[] fileNameList={};
    if(file.exists()) {
        fileNameList=file.list(new FolderFilter(extensions));
    }
    return fileNameList;
}

/**
 * 對文件列表按照指定方式排序,並返回文件名
 */
public String getLastestFile(String dirPath,String extensions){
    File  file = new File(dirPath);
    String retName="";
    if(file.exists()) {
        String[] fileNameList=file.list(new FolderFilter(extensions));
        if(null!=fileNameList&&fileNameList.length>0){
            Arrays.sort(fileNameList, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    String filedate=o1.substring(o1.lastIndexOf("_")+1);
                    filedate=filedate.substring(0, filedate.indexOf("."));
                    int i = Integer.parseInt(String.valueOf(filedate));

                    filedate=o2.substring(o2.lastIndexOf("_")+1);
                    filedate=filedate.substring(0, filedate.indexOf("."));
                    int j = Integer.parseInt(String.valueOf(filedate));

                    if (i < j) return 1;
                    if (i > j) return -1;
                    return 0;
                }
            });
            retName=fileNameList[0];
        }

    }
    return retName;

}

壓縮與解壓縮

/**
 * 功能:壓縮多個文件成一個zip文件
 * @param fileNameArray:源文件名列表
 * @param zipName:壓縮後的文件名
 */
public void zipFiles(String dirPath,String filePath,String[] fileNameArray, String zipName) throws Exception {
    File[] fileArray=new File[fileNameArray.length];
    for(int i=0;i<fileArray.length;i++){
        File zipfile = new File("D:\\xlsx"+File.separator+fileNameArray[i]);
        if(zipfile.exists()){
            fileArray[i]=zipfile;
        }
    }

    if(!new File(dirPath).exists()){
        new File(dirPath).mkdirs();
    }
    File zipfile = new File(filePath);
    zipFiles(fileArray,zipfile);
}

/**
 * 功能:壓縮多個文件成一個zip文件
 * @param fileArray:源文件列表
 * @param zipfile:壓縮後的文件
 */
public void zipFiles(File[] fileArray, File zipfile) throws Exception {
    byte[] buf = new byte[2048];
    if(zipfile.exists()){
        Boolean isDelete=zipfile.delete();
        if(!isDelete){
            throw new Exception("未成功刪除文件,請關閉使用該文件的所有進程或者流!!");
        }
    }
    //ZipOutputStream類:完成文件或文件夾的壓縮
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
    FileInputStream in=null;
    try{
        for (int i = 0; i < fileArray.length; i++) {
            in = new FileInputStream(fileArray[i]);
            out.putNextEntry(new ZipEntry(fileArray[i].getName()));
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
    }catch (Exception e) {
        e.printStackTrace();
    }finally {
        if(null!=in){
            in.close();
        }
        out.close();
    }
}

/**
 * 功能:解壓縮
 * @param zipfile:需要解壓縮的文件
 * @param descDir:解壓後的目標目錄
 */
public void unZipFiles(File zipfile, String descDir) {
    InputStream in=null;
    OutputStream out=null;
    ZipFile zf =null;
    try {
        zf=new ZipFile(zipfile);
        for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            in = zf.getInputStream(entry);
            out = new FileOutputStream(descDir + zipEntryName);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(null!=in){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if(null!=out){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null!=zf){
            try {
                zf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

文件轉化成byte[]

/**
 * 文件轉byte數組
 *
 * @param filename
 * @return
 * @throws IOException
 */
public static byte[] fileToByteArray(String dirPath,String filename) throws IOException {
    File file = new File(dirPath+ File.separator +filename);
    if (!file.exists()) {
        throw new FileNotFoundException(filename);
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
    BufferedInputStream in = null;
    try {
        in = new BufferedInputStream(new FileInputStream(file));
        int buf_size = 2048;
        byte[] buffer = new byte[buf_size]; //buff用於存放循環讀取的臨時數據
        int len = 0;
        while (-1 != (len = in.read(buffer, 0, buf_size))) {
            bos.write(buffer, 0, len);
        }
        return bos.toByteArray();//轉換之後的結果
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        if(null!=in){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        bos.close();
    }
}

excel

maven配置

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>
/**
 *
 * @param title         sheet名
 * @param headers       sheet標題
 * @param dataset       要寫入的數據,傳入普通的java bean集合
 * @param outStream     文件輸出流,此參數決定了文件名及文件存儲路徑
 * @param dataPattern   日期格式    yyyy-MM-dd-HH-mm-ss
 * @return Map          code 0成功-1失敗  mes 相關信息
 */
public Map<String, Object> exportExcel(String title, String[] headers, Collection<T> dataset,InputStream inputStream, OutputStream outStream, String dataPattern,Boolean is2003Excel) {

    //  返回值map
    Map<String, Object> retMap = new HashMap<String, Object>();
    // 聲明一個工作薄
    Workbook workbook = null;
        //ByteArrayOutputStream byteOutStream=new ByteArrayOutputStream();
    try {
        if (is2003Excel) {
            workbook = new HSSFWorkbook(inputStream);
        } else {
            workbook = new XSSFWorkbook(inputStream);
        }
    }  catch (IOException e) {
        e.printStackTrace();
        if (is2003Excel) {
            workbook = new HSSFWorkbook();
        } else {
            // 這裏1000是在內存中的數量,如果大於此數量時,會寫到硬盤,以避免在內存導致內存溢出   
            //new SXSSFWorkbook(1000);  
            workbook = new XSSFWorkbook();
        }
    }

    try {
        /*
        //sheetNum 第n個sheet 
        //MAXROW 每個表單最大允許行數
        int leng=MAXROW;
        for(int sheetNum=0;sheetNum<=size/MAXROW;sheetNum++){ 
            Sheet sheet = workbook.createSheet(title+"-"+sheetNum);
            //list中第num條數據
            for(;num<=leng&&num<=size;num++){

            }
            leng+=MAXROW;
        }
        */
        // 生成一個表格
        Sheet sheet = workbook.createSheet(title);
        // 生成一個樣式
        CellStyle style = workbook.createCellStyle();
        // 設置這些樣式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一個字體
        Font font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字體應用到當前的樣式
        style.setFont(font);
        // 生成並設置另一個樣式
        CellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一個字體
        Font font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字體應用到當前的樣式
        style2.setFont(font2);

//            // 聲明一個畫圖的頂級管理器
//            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 定義註釋的大小和位置,詳見文檔
//            HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
        // 設置註釋內容
//            comment.setString(new HSSFRichTextString("可以添加註釋!"));
        // 設置註釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.
        //comment.setAuthor("科印");

        // 產生表格標題行
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(style);
            RichTextString text=null;
            if (is2003Excel) {
                text = new HSSFRichTextString(headers[i]);
            } else {
                text = new XSSFRichTextString(headers[i]);
            }
            cell.setCellValue(text);
        }

        // 遍歷集合數據,產生數據行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
//                int firstImgNo = imgNo;
            index++;
            row = sheet.createRow(index);
            Object t = (T) it.next();
            // 利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(style2);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Class<? extends Object> tCls = t.getClass();
                Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                Object value = getMethod.invoke(t, new Object[] {});
                // 判斷值的類型後進行強制類型轉換
                String textValue = "";

                if (value != null) {
                    if (value instanceof byte[]) {
                        // 有圖片時,設置行高爲80px;
                        row.setHeightInPoints(80);
                        // 設置圖片所在列寬度爲100px,注意這裏單位的一個換算
                        //sheet.setColumnWidth(i, (short) (35.7 * 100));
                        sheet.setColumnWidth(i, 30 * 256);
                        // sheet.autoSizeColumn(i);
                        byte[] bsValue = (byte[]) value;
//                            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) (firstImgNo),index, (short) (firstImgNo), index);
//                            anchor.setAnchorType(2);
//                            patriarch.createPicture(anchor,workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));firstImgNo++;
                    } else if (value instanceof Date) {
                        Date date = (Date) value;
                        SimpleDateFormat sdf = new SimpleDateFormat(dataPattern);
                        textValue = sdf.format(date);
                    } else {
                        // 其它數據類型都當作字符串
                        textValue = value.toString();
                    }
                }

                if (textValue != null && !textValue.trim().equals("")) {
                    int length = textValue.getBytes().length;
                    int setLength = length * 256;
                    if (setLength > 65280) {
                        setLength = 65280;
                    }
                    sheet.setColumnWidth(i, setLength);
                    cell.setCellValue(textValue);
                } else {
                    sheet.setColumnWidth(i, 30 * 256);
                    cell.setCellValue("");
                }
            }
        }

        workbook.write(outStream);
        retMap.put("code",0);
        retMap.put("mes","excel寫入完成");
        //retMap.put("data",byteOutStream.toByteArray());
    }catch (Exception e){
        retMap.put("code",-1);
        retMap.put("mes","excel寫入失敗:"+e.getMessage());
    }finally {
        try {
            if(inputStream!=null){
                inputStream.close();
            }
            if(outStream != null){
                outStream.flush();
                outStream.close();
            }
        }catch (Exception e){
            retMap.put("code",-1);
            retMap.put("mes","excel寫入失敗:"+e.getMessage());
        }
    }
    return retMap;
}

// 是否是2003的excel,返回true是2003
public static boolean is2003Excel(String filePath) {

    return filePath.matches("^.+\\.(?i)(xls)$");

}

// 是否是2007的excel,返回true是2007
public static boolean is2007Excel(String filePath) {
    //^ 表示以...開頭
    //. 匹配除換行符 \n 之外的任何單字符
    //+ 匹配前面的子表達式一次或多次
    //根據 Java Language Specification 的要求,Java 源代碼的字符串中的反斜線被解釋爲 Unicode 轉義或其他字符轉義。因此必須在字符串字面值中使用兩個反斜線,表示正則表達式受到保護,不被 Java 字節碼編譯器解釋。
    //(?i)即匹配時不區分大小寫
    //$匹配輸入字符串的結尾位置
    return filePath.matches("^.+\\.(?i)(xlsx)$");

}
發佈了35 篇原創文章 · 獲贊 5 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章