1.你的需求是txt中,每行一个汉词没有其他内容吗?
2.最后输出txt中包含哪些汉字和他们的个数?
是这样的吗?
示例
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ReaderTxt {
/**
* @Description:读取文件,并记录汉词及次数
* @param path - 文件地址
* @return
* @throws
*/
public static MapgetFileContent(String path) {
Mapmap = new HashMap ();
File file = new File(path);
InputStreamReader read = null;
BufferedReader reader = null;
try {
read = new InputStreamReader(new FileInputStream(file), "gbk");
reader = new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null) {
if (map.containsKey(line)) {
int value = map.get(line) + 1;
map.put(line, value);
} else {
map.put(line, 1);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read != null) {
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return map;
}
public static void main(String[] args) {
Mapmap = ReaderTxt.getFileContent("d:/data.txt");
Setkeys = map.keySet();
for (Iteratorit = keys.iterator(); it.hasNext();) {
String key = it.next();
System.out.print("汉词:" + key);
System.out.println(",出现次数:" + map.get(key));
}
}
}
用一个HashMap