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 Map<String, Integer> getFileContent(String path) {
Map<String, Integer> map = new HashMap<String, Integer>();
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) {
Map<String, Integer> map = ReaderTxt.getFileContent("d:/data.txt");
Set<String> keys = map.keySet();
for (Iterator<String> it = keys.iterator(); it.hasNext();) {
String key = it.next();
System.out.print("汉词:" + key);
System.out.println(",出现次数:" + map.get(key));
}
}
}
追问最后输出是汉词,和他们的个数,而不是单单一个汉字的个数
追答示例贴上面了,自己看下!~
有问题再追问,good luck!