这里书中写的是charactorProcess(File file, String destFile)
这里被我改成,(String file, String destFIle)
一个代表现有的文件和要新建的文件
代码:
package com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
public class FileRead {
public static String replace(String line){
//创建一个HashMap存储全角和半角字符之间的对应关系
HashMap map = new HashMap();
map.put(",", ",");
map.put("。", ".");
map.put("〈", "<");
map.put("〉", ">");
map.put("|", "|");
map.put("《", "<");
map.put("》", ">");
map.put("[", "[");
map.put("]", "]");
map.put("?", "?");
map.put(""", "\"");
map.put(":", ":");
map.put("﹑", ",");
map.put("(", "(");
map.put(")", ")");
map.put("【", "[");
map.put("】", "]");
map.put("-", "-");
map.put(" ̄", "~");
map.put("!", "!");
map.put("`", "`");
map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
map.put("4", "4");
map.put("5", "5");
map.put("6", "6");
map.put("7", "7");
map.put("8", "8");
map.put("9", "9");
int length = line.length();
for(int i = 0; i < length; i++){
String charat = line.substring(i, i + 1);
if(map.get(charat) != null){
line = line.replace(charat, (String)map.get(charat));
}
}
return line;
}
public static File charactoProcess(String string, String destFile){
try{
//创建一个输出流,用于写新文件
BufferedWriter writer = new BufferedWriter(new FileWriter(destFile));
//创建一个输入流,用于读取文件
BufferedReader reader = new BufferedReader(new FileReader(string));
String line = reader.readLine();
while(line != null){
//调用replace方法替换所有的全角字符
String newline = replace(line);
//将替换后的String写入新的文件
writer.write(newline);
//写入行分隔符
writer.newLine();
line = reader.readLine();
}
reader.close();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
return new File(destFile);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FileRead b = new FileRead();
b.charactoProcess("E:\\Lucene项目\\钢铁是怎么样练成的.txt", "E:\\Lucene项目\\目标文件.txt");
}
}