File file=new File("文件路径")
BufferedReader br = new BufferedReader(new FileReader(file))
String line = null
//定义一个map集合保存单词和单词出现的个数
TreeMap<String,Integer> tm = new TreeMap<String,Integer>()
//读取文件
while((line=br.readLine())!=null){
line.toLowerCase()
String reg1 = "\\s+"
String reg2 ="\\w+"
//将读取的文本进行分割
String str[] = line.split(reg1)
for(String s: str){
if(s.matches(reg2)){
//判断集合中是否已经存在该单词,如果存在则个数加一,否则将单词添加到 //集合中,且个数置为1
if(!tm.containsKey(s)){
tm.put(s,1)
}else{
tm.put(s,tm.get(s)+1)
}
}
}
}
System.out.println(tm)
}
package file.system.demo.exceptionimport java.io.File
import java.io.FileNotFoundException
import java.io.FileWriter
import java.io.IOException
import java.util.ArrayList
import java.util.Collections
import java.util.List
import java.util.Scanner
import java.util.regex.Matcher
import java.util.regex.Pattern
public class FileManpulation {
public static List<String > getLowerCaseWords(File file) {
Scanner scanner = null
Pattern pattern = Pattern.compile("[a-zA-Z]+")
String text = ""
List<String > words = new ArrayList<>()
try {
scanner = new Scanner(file)
} catch (FileNotFoundException e) {
e.printStackTrace()
}
if(scanner!=null){
while(scanner.hasNextLine()){
text+=scanner.nextLine()
}
scanner.close()
}
//System.out.println(text)
Matcher matcher = pattern.matcher(text)
while (matcher.find()){
words.add(matcher.group().toLowerCase())
}
return words
}
/**
*
* @param words
* @param file 输入文件
* void
*/
public static void WriteToFile(List<String> words ,File file){
Collections.sort(words)//排序
FileWriter writer=null
try {
writer = new FileWriter(file)
for (String word : words) {
writer.write(word+" ")
}
} catch (IOException e) {
e.printStackTrace()
}
finally {
if(writer!=null){
try {
writer.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
}
static class InnerTest{
public static void main(String[] args) {
File file = new File("D:\\test.txt")
List<String> words=getLowerCaseWords(file)
WriteToFile(words,new File("D:\\in.txt"))
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)