Java实现offic转pdf在线预览

版权声明:作者:她如花似玉 转载请标明出处,原文地址: http://blog.csdn.net/qq_32566003 https://blog.csdn.net/qq_32566003/article/details/81699075

感谢https://blog.csdn.net/qq_28533563/article/details/72676425的贡献,本文根据自己需要作出总结

使用Aspose转换为pdf

本文所用jar包

<dependency>
			<groupId>com.aspose</groupId>
			<artifactId>aspose-words</artifactId>
			<version>16.8.0</version>
		</dependency>
		<dependency>
			<groupId>com.aspose</groupId>
			<artifactId>aspose-pdf</artifactId>
			<version>11.8.0</version>
		</dependency>
		<dependency>
			<groupId>com.aspose</groupId>
			<artifactId>aspose-cells</artifactId>
			<version>9.0.0</version>
		</dependency>
		<dependency>
			<groupId>com.aspose</groupId>
			<artifactId>aspose-slides</artifactId>
			<version>16.7.0</version>
		</dependency>
Aspose官网下载Aspose的Java版本

* Aspose.words 
* Aspose.cells(Excel) 
* Aspose.slides(PPT) 
* Aspose.pdf 

但是小编遇到一个坑哈,就是官网下载提示
 

java.lang.IllegalStateException: The signature is invalid.  
    at com.Aspose.words.da.a(License.java:757)  
    at com.Aspose.words.da.a(License.java:617)  
    at com.Aspose.words.da.c(License.java:376)  
    at com.Aspose.words.da.ar(License.java:345)  
    at com.Aspose.words.License.setLicense(License.java:226)  
    ......  

最终在http://blog.sina.com.cn/s/blog_9783605e0102uztz.html查看到原来是收费的,自己搞破解就比较麻烦,所以找强大的度娘搜索到破解版的

本文所用版本如下

Aspose.words 16.8.0 
Aspose.cells 9.0.0 
Aspose.slides 16.7.0 
Aspose.pdf 11.8.0 

jar包下载

Aspose注册工具类

package com.ruoyi.framework.zhjtets.util;
import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.InputStream;
/**
 * Created by software on 2018/8/13.
 */
public class AsposeLicenseUtil {
    private static InputStream inputStream = null;

    private static Logger logger = Logger.getLogger(AsposeLicenseUtil.class);

    /**
     * 获取License的输入流
     *
     * @return
     */
    private static InputStream getLicenseInput() {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            String path = contextClassLoader.getResource("license.xml").toURI().getPath();
            inputStream = new FileInputStream(path);

        } catch (Exception e) {
            logger.error("license not found!", e);
        }
        return inputStream;
    }

    /**
     * 设置License
     *
     * @return true表示已成功设置License, false表示失败
     */
    public static boolean setWordsLicense() {
        InputStream licenseInput = getLicenseInput();
        if (licenseInput != null) {
            try {
                com.aspose.words.License aposeLic = new com.aspose.words.License();
                aposeLic.setLicense(licenseInput);
                return aposeLic.getIsLicensed();
            } catch (Exception e) {
                logger.error("set words license error!", e);
            }
        }
        return false;
    }

    /**
     * 设置License
     *
     * @return true表示已成功设置License, false表示失败
     */
    public static boolean setCellsLicense() {
        InputStream licenseInput = getLicenseInput();
        if (licenseInput != null) {
            try {
                com.aspose.cells.License aposeLic = new com.aspose.cells.License();
                aposeLic.setLicense(licenseInput);
                return true;
            } catch (Exception e) {
                logger.error("set cells license error!", e);
            }
        }
        return false;
    }

    /**
     * 设置License
     *
     * @return true表示已成功设置License, false表示失败
     */
    public static boolean setSlidesLicense() {
        InputStream licenseInput = getLicenseInput();
        if (licenseInput != null) {
            try {
                com.aspose.slides.License aposeLic = new com.aspose.slides.License();
                aposeLic.setLicense(licenseInput);
                return aposeLic.isLicensed();
            } catch (Exception e) {
                logger.error("set ppt license error!", e);
            }
        }
        return false;
    }

    /**
     * 设置Aspose PDF的license
     * @return true表示设置成功,false表示设置失败
     */
    public static boolean setPdfLicense() {
        InputStream licenseInput = getLicenseInput();
        if (licenseInput != null) {
            try {
                com.aspose.pdf.License aposeLic = new com.aspose.pdf.License();
                aposeLic.setLicense(licenseInput);
                return true;
            } catch (Exception e) {
                logger.error("set pdf license error!", e);
            }
        }
        return false;
    }
}

word文档转换代码实例

package com.ruoyi.framework.zhjtets.service.impl;
import com.aspose.words.Document;
import com.aspose.words.PdfSaveOptions;
import com.aspose.words.SaveFormat;
import com.ruoyi.framework.zhjtets.util.AsposeLicenseUtil;
import com.ruoyi.framework.zhjtets.service.File2PdfService;
import com.ruoyi.framework.zhjtets.util.ResponseMap;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by software on 2018/8/13.
 */
public class Doc2PdfServiceImpl implements File2PdfService {
    @Override
    public ResponseMap convert2Pdf(InputStream inputStream, OutputStream outputStream) {
        ResponseMap responseMap=ResponseMap.getInstance();
        try {
            if (AsposeLicenseUtil.setWordsLicense()) {
                Document doc = new Document(inputStream);
                PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
                pdfSaveOptions.setSaveFormat(SaveFormat.PDF);
                pdfSaveOptions.getOutlineOptions().setHeadingsOutlineLevels(3); // 设置3级doc书签需要保存到pdf的heading中
                pdfSaveOptions.getOutlineOptions().setExpandedOutlineLevels(1); // 设置pdf中默认展开1级

                doc.save(outputStream, pdfSaveOptions);
                inputStream.close();
                outputStream.flush();
                outputStream.close();
                 responseMap=responseMap.isDocSuccess();
                return responseMap;
            } else {
                responseMap=responseMap.isLicenseError();
                return responseMap;
            }
        } catch (Exception e) {
            responseMap=responseMap.isDocToPdfError();
            return  responseMap;
        }
    }
}

execl文档转换代码实例

package com.ruoyi.framework.zhjtets.service.impl;

import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import com.ruoyi.framework.zhjtets.service.File2PdfService;
import com.ruoyi.framework.zhjtets.util.AsposeLicenseUtil;
import com.ruoyi.framework.zhjtets.util.ConvertStatus;
import com.ruoyi.framework.zhjtets.util.ResponseMap;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by software on 2018/8/13.
 */
public class Excel2PdfServiceImpl implements File2PdfService {
    @Override
    public ResponseMap convert2Pdf(InputStream inputStream, OutputStream outputStream) {
        ResponseMap responseMap=ResponseMap.getInstance();
        try {
            if (AsposeLicenseUtil.setCellsLicense()) {
                long start = System.currentTimeMillis();

                Workbook workbook = new Workbook(inputStream);
                workbook.save(outputStream, SaveFormat.PDF);

                // TODO 当excel宽度太大时,在PDF中会拆断并分页。此处如何等比缩放。
                /*
                // 将不同的sheet单独保存为pdf
                //Get the count of the worksheets in the workbook
                int sheetCount = workbook.getWorksheets().getCount();

                //Make all sheets invisible except first worksheet
                for (int i = 1; i < workbook.getWorksheets().getCount(); i++)
                {
                    workbook.getWorksheets().get(i).setVisible(false);
                }
                // workbook.save(outputStream, SaveFormat.PDF);

                //Take Pdfs of each sheet
                for (int j = 0; j < workbook.getWorksheets().getCount(); j++)
                {
                    Worksheet ws = workbook.getWorksheets().get(j);
                    workbook.save("E:/temp_" + ws.getName() + ".pdf");

                    if (j < workbook.getWorksheets().getCount() - 1)
                    {
                        workbook.getWorksheets().get(j + 1).setVisible(true);
                        workbook.getWorksheets().get(j).setVisible(false);
                    }
                }
                */

                inputStream.close();
                outputStream.flush();
                outputStream.close();
                responseMap=responseMap.isDocSuccess();
                return responseMap;
            } else {
                responseMap=responseMap.isLicenseError();
                return responseMap;
            }
        } catch (Exception e) {
            responseMap=responseMap.isExcelToPdfError();
            return responseMap;
        }
    }
}

ppt文档转换代码实例

package com.ruoyi.framework.zhjtets.service.impl;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import com.ruoyi.framework.zhjtets.service.File2PdfService;
import com.ruoyi.framework.zhjtets.util.AsposeLicenseUtil;
import com.ruoyi.framework.zhjtets.util.ConvertStatus;
import com.ruoyi.framework.zhjtets.util.ResponseMap;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by software on 2018/8/13.
 */
public class PPT2PdfServiceImpl implements File2PdfService {
    @Override
    public ResponseMap convert2Pdf(InputStream inputStream, OutputStream outputStream) {
        ResponseMap responseMap=ResponseMap.getInstance();
        try {
            if (AsposeLicenseUtil.setSlidesLicense()) {

                Presentation presentation = new Presentation(inputStream);
                presentation.save(outputStream, SaveFormat.Pdf);

                inputStream.close();
                outputStream.flush();
                outputStream.close();
                responseMap=responseMap.isDocSuccess();
                return responseMap;
            } else {
                responseMap=responseMap.isLicenseError();
                return responseMap;
            }
        } catch (Exception e) {
            responseMap=responseMap.isPpttoPdfError();
            return responseMap;
        }
    }
}

File2PdfService 

package com.ruoyi.framework.zhjtets.service;

import com.ruoyi.framework.zhjtets.util.ConvertStatus;
import com.ruoyi.framework.zhjtets.util.ResponseMap;

import java.io.InputStream;
import java.io.OutputStream;
/**
 * Created by software on 2018/8/13.
 */
public interface File2PdfService {
    /**
     * 将输入文件转换为PDF文件。
     * <br/>
     * <em>注意:输入及输出流在该方法中不会主动关闭,请调用完成后自己关闭!</em>
     * @param inputStream 输入流
     * @param outputStream 输出流
     * @return ConvertStatus 转换状态
     */
    public ResponseMap convert2Pdf(InputStream inputStream, OutputStream outputStream);
}

附件下载

fileName=fileName.substring(0,url.indexOf("."));
ResponseMap responseMap =downLoad(fileName,url);


public ResponseMap downLoad(String fileName,String filePath){
        ResponseMap responseMap = ResponseMap.getInstance();
        String pathName = PreviewUtils.savePath();
        Boolean isFile = PreviewUtils.downLoadFromUrl(filePath,fileName,pathName);
        if (isFile) {
            try {
                responseMap = PreviewUtils.officeConversionPDF(fileName);
            } catch (Exception e) {
                logger.error("附件文档转换出错" + e.getMessage());
            }
        }
        return responseMap;
    }

在线预览工具类

package com.ruoyi.framework.zhjtets.util;


import com.ruoyi.framework.zhjtets.controller.CourseController;
import com.ruoyi.framework.zhjtets.service.File2PdfService;
import com.ruoyi.framework.zhjtets.service.impl.Doc2PdfServiceImpl;
import com.ruoyi.framework.zhjtets.service.impl.Excel2PdfServiceImpl;
import com.ruoyi.framework.zhjtets.service.impl.PPT2PdfServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * Created by software on 2018/8/13.
 * 在线预览工具类
 * 文件下载工具
 */
public class PreviewUtils {
    private static Logger logger = LoggerFactory.getLogger(PreviewUtils.class);
    //转换服务
    private static File2PdfService fileConvertService;

    /**
     * office转换PDF
     * @param fileName 需要转换的文件名
     * @return
     * @throws Exception
     */
    public static ResponseMap officeConversionPDF(String fileName) throws Exception{
        ResponseMap responseMap=ResponseMap.getInstance();
        //获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
        String fileNames = fileName.substring(0,fileName.lastIndexOf("."));
        //根据后缀判断文件类型实例化对应服务层
        if (StringUtils.equalsIgnoreCase(suffix,"docx") || StringUtils.equalsIgnoreCase(suffix,"doc")){
            fileConvertService = new Doc2PdfServiceImpl();
        }else if (StringUtils.equalsIgnoreCase(suffix,"pptx") || StringUtils.equalsIgnoreCase(suffix,"ppt")){
            fileConvertService = new PPT2PdfServiceImpl();
        }else if (StringUtils.equalsIgnoreCase(suffix,"xlsx") || StringUtils.equalsIgnoreCase(suffix,"xls")){
            fileConvertService = new Excel2PdfServiceImpl();
        }
        //获取需要转换文档的所在路径
        File officeFile = new File(savePath()+File.separator+fileName);
        File outputFile = new File(outPDFPath(fileNames) +File.separator+ fileNames+".pdf");//PDF保存文件路径
        //如果文件是 PDF 不用转换直接复制到指定目录
        if (StringUtils.equalsIgnoreCase(suffix,"pdf")){
            FileRWUtils.copyFile(officeFile.getPath(),outPDFPath(fileNames));
            return responseMap;
        }
        if (!outputFile.exists()){
            InputStream inputStream = new FileInputStream(officeFile);
            OutputStream outputStream = new FileOutputStream(outputFile);
            //开始转换
            responseMap = fileConvertService.convert2Pdf(inputStream, outputStream);
        }else{
            outputFile.delete();
            InputStream inputStream = new FileInputStream(officeFile);
            OutputStream outputStream = new FileOutputStream(outputFile);
            //开始转换
            responseMap = fileConvertService.convert2Pdf(inputStream, outputStream);
        }
        return responseMap;
    }

    /**
     * 根据PDF文件名获取PDF存储地址
     * @param fileName PDF文件名
     * @return
     *  没有加.toURI() 有可能中文路径会乱码 加上获取会出错
     */
    public static String outPDFPath(String fileName) throws Exception{
        String pathName = PreviewUtils.class.getClassLoader().getResource("").getPath();
        pathName=pathName.substring(0,pathName.indexOf("/target"));
        pathName+="/src/main/resources/static/";
        //文件保存位置 如果文件夹不存在创建文件夹
        File saveDir = new File(pathName+File.separator+"outputFile");
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        return saveDir.getPath();
    }

    /**
     * 获取文件保存路径
     * @return
     */
    public static String savePath(){
        String pathName = PreviewUtils.class.getClassLoader().getResource("").getPath();
        pathName=pathName.substring(0,pathName.indexOf("/target"));
        pathName+="/src/main/resources/static/";
        //文件保存位置 如果文件夹不存在创建文件夹
        File saveDir = new File(pathName+File.separator+"convertFile");
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        return saveDir.getPath();
    }

    /**
     * 从网络Url中下载文件
     * @param urlStr 下载地址
     * @param fileName 文件名
     * @param savePath  保存地址
     * @throws IOException
     */
    public static boolean  downLoadFromUrl(String urlStr,String fileName,String savePath){
        File file = new File(savePath+File.separator+fileName);
        //文件是否已存在
        if(file.exists()){
            return true;
        }
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为30秒
            conn.setConnectTimeout(30*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);
            FileOutputStream fos = new FileOutputStream(file);
            if (getData == null){
                return false;
            }
            fos.write(getData);
            if(fos!=null){
                fos.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("附件下载转换PDF出错!",e);
        }
        return false;
    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}

页面

<iframe th:src="${url}" name="main" marginwidth="0" id="fs_main" marginheight="0" frameborder="0" width="100%"
        style="height: 700px;"></iframe>

license.xml

<License>
<Data>
  <Products>
    <Product>Aspose.Total for Java</Product>
    <Product>Aspose.Words for Java</Product>
  </Products>
  <EditionType>Enterprise</EditionType>
  <SubscriptionExpiry>20991231</SubscriptionExpiry>
  <LicenseExpiry>20991231</LicenseExpiry>
  <SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

FileRWUtils 工具类 

package com.ruoyi.framework.zhjtets.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Created by software on 2018/8/14.
 */
public class FileRWUtils {
    private static Logger LOGGER = LoggerFactory.getLogger(FileRWUtils.class);

    /**
     * 创建文件目录
     * @param dir 文件目录
     */
    /**
     * 创建文件目录是否成功
     * @param dir
     * @return  true为成功,false为失败
     */
    public static boolean mkdir(String dir) {
        try {
            String dirTemp = dir;
            File dirPath = new File(dirTemp);
            if (!dirPath.exists()) {
                return dirPath.mkdirs();
            }else{
                return true;
            }
        } catch (Exception e) {
            // e.printStackTrace();
//            LogUtil.error("-异常--dirPath->"+e.toString());
            LOGGER.error("创建文件目录操作出错: " + e.getMessage(), e);
            return false;
        }
    }

    /**
     * 判断文件是否存在
     * @param fileName 包含路径的文件名
     * @return
     */
    public static boolean isFileExists(String fileName) {
        String fileNameTemp = fileName;
        File filePath = new File(fileNameTemp);
        return filePath.exists();
    }
    /**
     * 新建文件
     * @param fileName  包含路径的文件名
     * @return  true创建成功 false 创建失败
     */
    public static boolean createFile(String fileName) {
        try {
            String fileNameTemp = fileName;
            File filePath = new File(fileNameTemp);
            if (!filePath.exists()) {
                return filePath.createNewFile();
            }else{
                return true;
            }
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("新建文件操作出错: " + e.getMessage(), e);
            return false;
        }
    }

    /**
     * 新建文件
     * @param fileName 包含路径的文件名
     * @param content 文件内容
     */
    public static void createFile(String fileName, String content) {
        try {
            String fileNameTemp = fileName;
            File filePath = new File(fileNameTemp);
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            FileWriter fw = new FileWriter(filePath);
            PrintWriter pw = new PrintWriter(fw);
            String strContent = content;
            pw.println(strContent);
            pw.flush();
            pw.close();
            fw.close();
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("新建文件操作出错: " + e.getMessage(), e);
        }
    }

    /**
     * 新建文件
     * @param fileName  包含路径的文件名
     * @param bytes     文件流数据
     */
    public static void createFile(String fileName, byte[] bytes) {
        try {
            if (bytes != null) {
                String fileNameTemp = fileName;
                File filePath = new File(fileNameTemp);
                if (!filePath.exists()) {
                    filePath.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(filePath);
                fos.write(bytes, 0, bytes.length);
                fos.flush();
                fos.close();
            }
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("新建文件操作出错: " + e.getMessage(), e);
        }
    }

    /**
     * 删除文件
     * @param fileName 包含路径的文件名
     */
    public static void delFile(String fileName) {
        try {
            String filePath = fileName;
            File delFile = new File(filePath);
            delFile.delete();
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("删除文件操作出错: " + e.getMessage(), e);
        }
    }

    /**
     * 删除文件夹
     * @param folderPath 文件夹路径
     */
    public static void delFolder(String folderPath) {
        try {
            // 删除文件夹里面所有内容
            delAllFiles(folderPath);
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            // 删除空文件夹
            myFilePath.delete();
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("删除文件夹操作出错:" + e.getMessage(), e);
        }
    }

    /**
     * 删除文件夹里面的所有文件
     * @param folderPath 文件夹路径
     */
    public static void delAllFiles(String folderPath) {
        try {
            File file = new File(folderPath);
            if (!file.exists()) {
                return;
            }
            if (!file.isDirectory()) {
                return;
            }
            String[] childFiles = file.list();
            File temp = null;
            for (int i = 0; i < childFiles.length; i++) {
                // File.separator:与系统有关的默认名称分隔符,在UNIX系统上,此字段的值为'/';在Microsoft Windows系统上,它为'\'
                if (folderPath.endsWith(File.separator)) {
                    temp = new File(folderPath + childFiles[i]);
                } else {
                    temp = new File(folderPath + File.separator + childFiles[i]);
                }
                if (temp.isFile()) {
                    temp.delete();
                }
                if (temp.isDirectory()) {
                    // 先删除文件夹里面的文件
                    delAllFiles(folderPath + "/" + childFiles[i]);
                    // 再删除空文件夹
                    delFolder(folderPath + "/" + childFiles[i]);
                }
            }
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("删除文件夹里面的所有文件操作出错:" + e.getMessage(), e);
        }
    }

    /**
     * 复制单个文件
     * @param srcFile 包含路径的源文件
     * @param dirDest 目标文件目录,若文件目录不存在则自动创建
     */
    public static void copyFile(String srcFile, String dirDest) {
        try {
            FileInputStream in = new FileInputStream(srcFile);
            mkdir(dirDest);
            FileOutputStream out = new FileOutputStream(dirDest + "/" + new File(srcFile).getName());
            int len;
            byte buffer[] = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("复制单个文件操作出错:" + e.getMessage());
        }
    }

    /**
     * 复制文件夹
     * @param oldPath 源文件夹路径
     * @param newPath 目标文件夹路径
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            // 如果文件夹不存在 则新建文件夹
            mkdir(newPath);
            File file = new File(oldPath);
            String[] files = file.list();
            File temp = null;
            for (int i = 0; i < files.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + files[i]);
                } else {
                    temp = new File(oldPath + File.separator + files[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
                    byte[] buffer = new byte[1024 * 2];
                    int len;
                    while ((len = input.read(buffer)) != -1) {
                        output.write(buffer, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                // 如果是子文件夹
                if (temp.isDirectory()) {
                    copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]);
                }
            }
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("复制文件夹操作出错:" + e.getMessage(), e);
        }
    }

    /**
     * 移动单个文件
     * @param oldPath 源文件路径
     * @param newPath 目标文件路径
     */
    public static void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }

    /**
     * 移动文件夹下面的所有文件
     * @param oldPath 源文件路径
     * @param newPath 目标文件路径
     */
    public static void moveFiles(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delAllFiles(oldPath);
    }

    /**
     * 移动文件夹
     * @param oldPath 源文件夹路径
     * @param newPath 目标文件夹路径
     */
    public static void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }

    /**
     * 读取文件数据
     * @param path 文件路径
     * @return
     */
    public static String readData(String path) {
        return readData(path, "UTF-8");
    }

    /**
     * 读取文件数据
     * @param path 文件路径
     * @param charsetName 字符集
     * @return
     */
    public static String readData(String path, String charsetName) {
        String dataString = new String();
        try {
            InputStream inputStream = new FileInputStream(path);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            byte[] data = outputStream.toByteArray();
            outputStream.close();
            inputStream.close();
            dataString = new String(data, charsetName);
        } catch (FileNotFoundException fe) {
            // fe.printStackTrace();
            dataString = null;
            LOGGER.error("FileNotFoundException---读取文件数据操作出错,找不到文件!", fe);
        } catch (UnsupportedEncodingException ue) {
            // ue.printStackTrace();
            dataString = null;
            LOGGER.error("UnsupportedEncodingException---读取文件数据操作出错,不支持的编码字符集!", ue);
        } catch (IOException ie) {
            // ie.printStackTrace();
            dataString = null;
            LOGGER.error("IOException---读取文件数据操作出错,IO异常!", ie);
        } catch (Exception e) {
            // e.printStackTrace();
            dataString = null;
            LOGGER.error("读取文件数据操作出错!", e);
        }
        return dataString;
    }



//       public static boolean writeDataToFile(String filePath,boolean append,String content){
//          if(content==null){
//              LogUtil.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content=null");
//              return false;
//          }
//          File file1 = new File(filePath);
//          Writer writer=null;
//          try {
//               //此处设置为true即可追加
//              writer = new BufferedWriter(
//                     new OutputStreamWriter(
//                             new FileOutputStream(file1,true), "UTF-8"));
//               //往文件写入
//              writer.write(content);
////            //换行
////            out.write("\r\n");
////            //继续追加
////            out.write("def");
//              //刷新IO内存流
//              writer.flush();
//          } catch (IOException e) {
//              // TODO Auto-generated catch block
//              e.printStackTrace();
//              LogUtil.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content.length="+content.length()+(content.length()<50?content:""),e);
//              return false;
//          } finally{
//               //关闭
//              if(null!=writer){
//              try {
//                  writer.close();
//              } catch (IOException e) {
//                  // TODO Auto-generated catch block
//                  e.printStackTrace();
//                  LogUtil.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content.length="+content.length()+(content.length()<50?content:""),e);
//                  return false;
//              }
//              }
//          }
//          return true;
//
//      }

    public static boolean writeDataToFile(String filePath,boolean append,String content){
        if(content==null){
            LOGGER.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content=null");
            return false;
        }

        FileWriter out = null;
        try {
            //此处设置为true即可追加
            out = new FileWriter(filePath, true);
            //往文件写入
            out.write(content);
//          //换行
//          out.write("\r\n");
//          //继续追加
//          out.write("def");
            //刷新IO内存流
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOGGER.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content.length="+content.length()+(content.length()<50?content:""),e);
            return false;
        } finally{
            //关闭
            if(null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    LOGGER.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content.length="+content.length()+(content.length()<50?content:""),e);
                    return false;
                }
            }
        }
        return true;

    }

//  public static boolean writeDataToFile(String filePath,boolean append,String content){
//      if(content==null){
//          LogUtil.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content=null");
//          return false;
//      }
//      OutputStreamWriter out=null;
//      try {
//           //此处设置为true即可追加
//           out =  new OutputStreamWriter(new FileOutputStream(filePath,true),"UTF-8");
//           //往文件写入
//          out.write(content);
////            //换行
////            out.write("\r\n");
////            //继续追加
////            out.write("def");
//          //刷新IO内存流
//          out.flush();
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//          LogUtil.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content.length="+content.length()+(content.length()<50?content:""),e);
//          return false;
//      } finally{
//           //关闭
//          if(null!=out){
//          try {
//              out.close();
//          } catch (IOException e) {
//              // TODO Auto-generated catch block
//              e.printStackTrace();
//              LogUtil.error("----writeDataToFile-->filePath:"+filePath+",append="+append+",content.length="+content.length()+(content.length()<50?content:""),e);
//              return false;
//          }
//          }
//      }
//      return true;
//
//  }

    /**
     * 逐行读取文件数据
     * @param path 文件路径
     * @return
     */
    public static Set<String> readDataLineByLine(String path) {
        Set<String> dataSet = new HashSet<String>();
        try {
            FileReader fr = new FileReader(path);
            BufferedReader br = new BufferedReader(fr);
            String line = null;
            while ((line = br.readLine()) != null) {
                dataSet.add(line);
            }
            br.close();
            fr.close();
        } catch (FileNotFoundException fe) {
            // fe.printStackTrace();
            LOGGER.error("FileNotFoundException---逐行读取文件数据操作出错,找不到文件!", fe);
        } catch (IOException ie) {
            // ie.printStackTrace();
            LOGGER.error("IOException---逐行读取文件数据操作出错,IO异常!", ie);
        } catch (Exception e) {
            // e.printStackTrace();
            LOGGER.error("逐行读取文件数据操作出错!", e);
        }
        return dataSet;
    }

    /**
     * 逐行读取文件数据为<key, value>的键值形式
     * @param path 文件路径
     * @return
     */
    public static Map<String, String> readDataAsMap(String path, String separator) {
        Map<String, String> dataMap = new LinkedHashMap<String, String>();
        if (separator != null && !separator.equals("")) {
            try {
                FileReader fr = new FileReader(path);
                BufferedReader br = new BufferedReader(fr);
                String line = null, key = null, value = null;
                while ((line = br.readLine()) != null) {
                    if (!line.equals("")) {
                        // 跳过注释行
                        if (line.startsWith("#")) {
                            continue;
                        }
                        if (line.contains(separator)) {
                            key = line.substring(0, line.indexOf(separator)).trim();
                            value = line.substring(line.indexOf(separator) + 1).trim();
                            dataMap.put(key, value);
                        }
                    }
                }
                br.close();
                fr.close();
            } catch (FileNotFoundException fe) {
                // fe.printStackTrace();
                LOGGER.error("FileNotFoundException---逐行读取文件数据为Map操作出错,找不到文件!", fe);
            } catch (IOException ie) {
                // ie.printStackTrace();
                LOGGER.error("IOException---逐行读取文件数据为Map操作出错,IO异常!", ie);
            } catch (Exception e) {
                // e.printStackTrace();
                LOGGER.error("逐行读取文件数据为Map操作出错!", e);
            }
        }
        return dataMap;
    }



    /**
     * 获取某个目录下以某个字符为前缀的所有文件
     * @param dataDirectory
     * @param namePreFix
     * @return
     */
    public static File[] getFileByNamePreFix(String dataDirectory,final String namePreFix){
        File dirFile =new File(dataDirectory);
        if(!dirFile.exists()){
            return null;
        }

        File[] dataFiles = dirFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if(name.startsWith(namePreFix)) {
                    return true;
                }

                return false;
            }
        });

        return dataFiles;
    }
}

end

猜你喜欢

转载自blog.csdn.net/qq_32566003/article/details/81699075