用java遍历所有文件夹,将word文件转换为txt格式

用Java代码,遍历文件夹及子文件夹,将其中的doc和docx文件批量转换为txt格式

文件夹结构

bbb文件夹

 ccc文件夹

加几个除word外的干扰项

 ddd文件夹

 依赖

    <dependencies>

        <dependency>
            <groupId>com.jacob</groupId>
            <artifactId>jacob</artifactId>
            <version>1.19</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/resources/lib/jacob.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-FINAL</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.10.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.10.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.9</version>
        </dependency>

        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>xdocreport</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
              
            <artifactId>fr.opensagres.xdocreport.document</artifactId>
              
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>org.apache.poi.xwpf.converter.core</artifactId>
            <version>1.0.6</version>
        </dependency>

        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
            <version>1.0.6</version>
        </dependency>

        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
            <version>1.0.6</version>
        </dependency>

    </dependencies>

代码

主方法

这里需要说明的是,同一文件夹中可能会存在A.doc和A.docx这样的情况,当转换为A.txt时后转换的会覆盖掉先前转换的,所以定义了两个路径输出到不同文件夹中来解决(当然也可以在文件名后加随机数等方法),不过这里就先不考虑这个问题,暂时写一个路径,可以根据自己需求修改

    public static void main(String[] args) throws Exception {
        try {
//            定义word文件所在路径
            String path="F:\\bbb";
//          定义输出txt文件所在路径
            String outdocPath = "F:\\zzz";
            String outdocxPath = "F:\\zzz";
            path = URLDecoder.decode(path, "UTF-8");
//            调用方法,遍历文件夹
            LinkedList<File> files = EveryFile.GetDirectory(path);
            for (int i = 0; i < files.size(); i++) {
//                word文件所在路径
                String filesName = String.valueOf(files.get(i));
//                word文件名
                String fileName=files.get(i).getName();
//                调用方法,进行转换
                WordToTxt.word2txt(filesName,fileName,outdocPath,outdocxPath);
            }
            System.out.println("转换完毕");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

遍历文件夹代码

    /**
     * 遍历文件夹
     * @param path
     * @return
     */
    public static LinkedList<File> GetDirectory(String path) {
        File file = new File(path);
        LinkedList<File> Dirlist = new LinkedList<File>(); // 保存待遍历文件夹的列表
        LinkedList<File> fileList = new LinkedList<File>();
        GetOneDir(file, Dirlist, fileList);// 调用遍历文件夹根目录文件的方法
        File tmp;
        while (!Dirlist.isEmpty()) {
            tmp = (File) Dirlist.removeFirst();// 从文件夹列表中删除第一个文件夹,并返回该文件夹赋给tmp变量
            // 遍历这个文件夹下的所有文件,并把
            GetOneDir(tmp, Dirlist, fileList);

        }
        return fileList;
    }

    // 遍历指定文件夹根目录下的文件
    private static void GetOneDir(File file, LinkedList<File> Dirlist,
                                  LinkedList<File> fileList) {
        // 每个文件夹遍历都会调用该方法
        File[] files = file.listFiles();

        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                Dirlist.add(f);
            } else {
                // 这里列出当前文件夹根目录下的所有文件,并添加到fileList列表中
                fileList.add(f);
                // System.out.println("file==>" + f);

            }
        }
    }

word转txt代码

    /**
     * 将word转换为txt
     *
     * @param filesName   word文件绝对路径 F:\bbb\ddd\周五.docx
     * @param fileName    word文件名 周五.docx
     * @param outdocPath  doc文件转txt输出路径
     * @param outdocxPath docx文件转txt输出路径
     * @throws Exception
     */
    public static void word2txt(String filesName, String fileName, String outdocPath, String outdocxPath) throws Exception {

        String fileType = new String("");
        fileType = filesName.substring(filesName.length() - 4, filesName.length());

        if (fileType.equals("docx")) {
//            要转换的文档全路径
            String docxPath = filesName;
//            转换后的文档全路径
            String docxtotxtPath = outdocxPath + "/" + fileName.substring(0, fileName.length() - 5) + ".txt";

            //得到.docx文件提取器
            XWPFWordExtractor docx = new XWPFWordExtractor(POIXMLDocument.openPackage(docxPath));
            //提取.docx正文文本
            String text = docx.getText();

            FileWriter writer = new FileWriter(docxtotxtPath);
            writer.write(text);
            writer.close();

        } else if (fileType.equals(".doc")) {
//            要转换的文档全路径
            String docPath = filesName;
//            转换后的文档全路径
            String doctotxtPath = outdocPath + "/" + fileName.substring(0, fileName.length() - 4) + ".txt";
            InputStream is = new FileInputStream(docPath);
            HWPFDocument wordDocument = new HWPFDocument(is);
            WordToTextConverter converter = new WordToTextConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());

            //对HWPFDocument进行转换
            converter.processDocument(wordDocument);
            Writer writer = new FileWriter(new File(doctotxtPath));
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            //是否添加空格
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "text");
            transformer.transform(
                    new DOMSource(converter.getDocument()),
                    new StreamResult(writer));
        }
    }

运行结果

 后记

word文件中的图片转换到txt后将不会保留。

代码一定存在可以优化的地方,一是水品有限,二是手头还有其他的事要忙,目前这些代码满足需要,所以暂时没有修改。各位大佬使用的时候根据自己需要修改,不足之处欢迎批评指正。

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值