读取txt文件
在Java里要对文件进行操作,需要用到IO流。
public static void main(String args[]){
File f = new File("test.txt");
try {
// InputStream 处理的是字节流,用read()的话每次读取的是一个byte
InputStream in = new FileInputStream(f);
// InputStreamReader 处理的是字符流,用read()的话每次读取一个字符
InputStreamReader reader = new InputStreamReader(in,"gbk");
// BufferReader 处理的是字符流,能够一行一行的读取文件
BufferedReader bufReader = new BufferedReader(reader);
int i = 1;
String line ="";
// readLine()每用一次读取一行
while((line = bufReader.readLine()) != null){
System.out.println("第"+ i + "行:"+line);
++i;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
输出:
操作doc文件
读取doc文件如果也用上面的方法的话,中文就会出现乱码:
要用Java Apache POI才能对doc文件进行操作,使用POI从doc文件读取数据时主要有两种方式:通过WordExtractor读和通过HWPFDocument读。首先先在Maven中引入poi-scratchpad的jar包(如果是docx文件则引入poi-ooxml的jar包 )
使用WordExtractor
WordExtractor的功能相比HWPFDocument的功能是要少的,在使用WordExtractor读文件时我们只能读到文件的文本内容和基于文档的一些属性,至于文档内容的属性等是无法读到的,并且WordExtractor无法修改doc文件。使用WordExtractor读取文件内容:
public static void main(String args[]){
File f = new File("test.doc");
try {
InputStream in = new FileInputStream(f);
WordExtractor ex = new WordExtractor(in);
System.out.println(ex.getText());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
使用HWPFDocument
因为我主要是为了修改doc文件的内容,所以用HWPFDocument。将文档中的中文字全部去除:
public static void main(String args[]){
File f = new File("test.doc");
try {
InputStream in = new FileInputStream(f);
HWPFDocument ex = new HWPFDocument(in);
Range range = ex.getRange();
/**
* 匹配中文字符 [\\u4e00-\\u9fa5]
* 中文标点符号,、; \\uff1b|\\uff0c|\\u3001
* 括号内容(包括括号) (\\(.*\\))
*/
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]|\\uff1b|\\uff0c|\\u3001|(\\(.*\\))",Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(range.text());
OutputStream os = new FileOutputStream(f);
// 找到中文字符并替换为“” 即删除
while (matcher.find( )) {
range.replaceText(matcher.group(),"");
}
// 将修改后的内容重新写入文档中
ex.write(os);
os.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
修改前:
修改后:
做这个功能是为了背单词,而一个文档5500个单词,308页内容,一个一个删除中文太麻烦了,所以想到了用代码实现