文件的读写(Java实训)
实训目的:
字符串处理、文件读写、集合的应用
实训要求:
自己先准备一个txt文件,文档里存有一篇英语短文。先一行行读取文件中的内容,并将一行行短文中的标点符号替换成空格,然后以空格作为划分标准,统计整个txt文档中每个单词出现的次数。

先放出文档英语文章。
article.txt
It also means those reflections of the diamond cannot be replaced by any kind of light or reflection, because the untrue reflection will not be a real diamond, and will not be able to spread out its resplendent and meaningful reflection of love to people about whom I care.
FileRead.java
package program6
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.util.HashMap
import java.util.Set
public class FileRead {
public static void main(String[] args) {
HashMap<String,Integer> m=new HashMap<>()
try {
BufferedReader reader=new BufferedReader(new FileReader("article.txt"))
String ss=null
while((ss=reader.readLine())!=null) {
String[] str=ss.trim().split("\s+")
for(int i=0i<str.lengthi++) {
String word=str[i].trim()
if(m.containsKey(word)) {
m.put(word, m.get(word)+1)
}else {
m.put(word, 1)
}
}
}
int cnt=0
System.out.println("统计各单词个数为:")
Set<String> st=m.keySet()
for(String k:st) {
if(k.hashCode()!=0){
char[] str=k.toCharArray()
for(int i=0i<str.lengthi++) {
if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) {
System.out.print(str[i])
}
}
System.out.println("出现了"+m.get(k.trim())+"次")
cnt++
}
}
} catch (IOException e) {
e.printStackTrace()
}
}
}






Comments NOTHING