在我下面的代码中,它从一个文件夹(假设该文件夹有 2000 多个文本文件)中读取 .txt 文件,并显示文本文档中存在的单词总数。
如果我仅从目录中读取 10-30 个文本文件,输出将按每个文本文件的顺序正确显示。
但是当我添加 2000 多个文本文件并立即从该文件夹中读取时,输出排列会折叠。(它以随机顺序显示)。
谁能建议我解决这个问题?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
public class duplicatestrings
{
public static void main(String[] args)
{
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("E:\\testfolder");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file1 = listOfFiles[i];
try {
String content = FileUtils.readFileToString(file1);
// System.out.println("asssdffsssssssssss = " + content);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader ins = null;
try {
ins = new BufferedReader (
new InputStreamReader(
new FileInputStream(file1)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "", str = "";
int a = 0;
int b = 0;
try {
while ((line = ins.readLine()) != null) {
str += line + " ";
b++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println("Total number of lines " +b);
//System.out.println(str);
/* int count =0;
try {
String input = ins.readLine();
String[] array = input.split(" ");
System.out.print("\nPlease enter word to be counted :");
String key = ins.readLine();
for(int s=0;i < array.length;i++){
if(array[s].equals(key))
count++;
}
System.out.print("\n The given word occured " + count + " times");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String s = st.nextToken();
a++;
}
// List<String> list = Arrays.asList(str.split(" "));
// Set<String> uniqueWords = new HashSet<String>(list);
// for (String word : uniqueWords) {
// System.out.println(word + a+ "\n" + Collections.frequency(list, word));}
System.out.println(" Total no of words=" + a );
}
}
}
而且我必须从所有文本文件/文件夹(目录)中获取不同且重复的词“无计数(仅)”。
欢迎提出建议。
最佳答案
在计算每个文件中的单词后,您可以将结果插入到 TreeSet 中,然后您可以按一致的顺序显示它们。键是文件名,值是字数。请参阅:how to sort Map values by key in Java
或者你可以对文件夹中的文件名进行排序,统计排序后的文件列表中的单词数:how to File.listFiles in alphabetical order?
关于java - 如何从java中的文本文件/文件夹中获取字数(不更改文件夹的读取顺序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34848879/