【发布时间】:2016-04-23 06:41:31
【问题描述】:
在我下面的代码中,它从一个文件夹中读取 .txt 文件(比如该文件夹有 2000 多个文本文件),并显示文本文档中存在的总字数。
如果我仅从目录中读取 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 );
}
}
}
而且我必须从所有文本文件/文件夹(目录)中获得不同且重复的单词“计数(仅)”。
欢迎提出建议。
【问题讨论】:
-
请更详细地在输出中表达您想要的内容。你想分别计算每个
.txt文件的字数吗?还有你说的这个命令是什么?当您在 Windows 资源管理器中看到文件时,文件的文件名是按字母顺序排列的吗? -
是的,我想为每个 .txt 文件分别计算字数。输出是随机显示的。一些文本文件是随机排列的。
-
如果我查看 (file1) 它只有 1000 个文件,但在我的目录文件夹中我有 2000 多个文件。但输出“total no of words”给出了所有 2000+ 个文件的计数。
-
还有
the output arrangement is collapsed.(it displays in random order)是什么意思,我看到你的输出只有总计没有文件名,所以你怎么知道它不正确?请记住,folder.listFiles(filter)的文件顺序可能与您在操作系统的File Explorer中看到的顺序不同。 -
我想要文件资源管理器中显示的字母顺序。我交叉检查了它
标签: java text hashmap filereader word-count