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;
}
}
}