java 读取doc并写入txt

package test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* poi-3.0.1-FINAL-20070705.jar
* poi-scratchpad-3.0.1-FINAL-20070705.jar
*/
import org.apache.poi.hwpf.extractor.WordExtractor;

public class Doc {

private String path = "d:\\doc";   //创建文件夹目录
private static String date = new SimpleDateFormat("yyyyMMddHHmmss")
    .format(new Date());
private static String doc = "d:\\doc\\" + date + ".txt";   //创建txt文件目录

/**
* 得到.doc文件的内容
*/
public String readDoc(String doc) throws Exception {
   // 创建输入流读取DOC文件
   FileInputStream in = new FileInputStream(new File(doc));
   // 创建WordExtractor
   WordExtractor extractor = new WordExtractor(in);
   // 对DOC文件进行提取
   String text = extractor.getText();

   //替换文件中的回车
   if (text.indexOf('\r') != -1) {
    text=text.replaceAll("\r", "\r\n");
   }
   if (text.indexOf('\n') != -1) {
    text=text.replaceAll("\n", "\r\n");
   }

   return text;
}

public static void main(String[] args) {
   String text = null;
   try {
    text = new Doc().readDoc("d:/1.doc");
   } catch (Exception e) {
    e.printStackTrace();
   }
   if (new Doc().newtxt()) {
    if (new Doc().insert(doc, text, false)) {
     System.out.println("true");
    } else {
     System.out.println("false");
    }
   }
}

/**
* 创建文件夹和文件
*/
public boolean newtxt() {
   try {
    /**//* 查找目录,如果不存在,就创建 */
    File dirFile = new File(path);
    if (!dirFile.exists()) {
     if (!dirFile.mkdir())
      throw new Exception("目录不存在,创建失败!");
    }
    /**//* 查找文件,如果不存在,就创建 */
    File file = new File(doc);
    System.out.println(date);
    if (!file.exists())
     if (!file.createNewFile())
      throw new Exception("文件不存在,创建失败!");
    return true;
   } catch (Exception e) {
    System.out.println(e.getMessage());
    return false;
   }
}

/**
* 将文本写入相应的文本中
*/
public boolean insert(String path, String content, boolean append) {
   BufferedWriter bw;
   File file;
   try {
    boolean addstr = append;
    System.out.println(date);
    file = new File(path);
    FileWriter fw = new FileWriter(file, addstr);
    bw = new BufferedWriter(fw);
    fw.write(content);
    fw.flush();
    fw.close();
    return true;
   } catch (Exception e) {
    e.getMessage();
    return false;
   }
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值