文件操作(文件过滤,压缩,导出到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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章