我是Java编程的新手,我正在尝试打印名称,从文件夹中读取多个文本文件并计算每个word文件的单词频率,当我在读取文件夹时,所有文本文件都被打印但是它们不是看了,请看代码。
import java.io.*;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class foldersearch
{
public static void main(String[] args)
{
// Directory path here
String path = "/home/sumeet/Documents/text files";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);
TreeMap<String, Integer> frequencyMap = new TreeMap<String, Integer>();
String currentLine="";
File textFile = new File(files); // SOME CHANGE IS REQUIRED HERE..?
try {
BufferedReader br = new BufferedReader(new FileReader(textFile));
while ((currentLine = br.readLine()) != null) {
currentLine = currentLine.toLowerCase();
StringTokenizer parser = new StringTokenizer(currentLine, " \t\n\r\f.,;:!?'");
while (parser.hasMoreTokens()) {
String currentWord = parser.nextToken();
Integer frequency = frequencyMap.get(currentWord);
if (frequency == null) {
frequency = 0;
}
frequencyMap.put(currentWord, frequency + 1);
}
}
br.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(frequencyMap);
}
}
}
}
}
输出:
nokia.txt
nokia.txt (No such file or directory)
{}
MainClass.txt
MainClass.txt (No such file or directory)
{}
2b.txt
2b.txt (No such file or directory)
{}
cn exercise 2.txt
cn exercise 2.txt (No such file or directory)
{}
2c.txt
2c.txt (No such file or directory)
{}
dummy.txt
dummy.txt (No such file or directory)
{}
readme.txt
readme.txt (No such file or directory)
{}
Kb.txt
Kb.txt (No such file or directory)
{}
all.txt
all.txt (No such file or directory)
{}
1b.txt
1b.txt (No such file or directory)
{}
todo.txt
todo.txt (No such file or directory)
{}
1c.txt
1c.txt (No such file or directory)
{}
2a.txt
2a.txt (No such file or directory)
{}
USE CASE.txt
USE CASE.txt (No such file or directory)
{}
答案 0 :(得分:1)
在尝试打开目录之前,需要将目录名称添加到文件名中。它目前正在尝试打开nokia.txt / 2b.txt / etc.从当前目录。
答案 1 :(得分:1)
尝试:
File textFile = new File(folder.getAbsolutePath() + File.separator + files);
答案 2 :(得分:1)
程序员需要学习的第一件事就是如何在遇到错误时弄清楚自己发生了什么。所以我们不会通过给出答案来帮助你(虽然我看到我们已经有了答案)。
所有程序员需要获得的另一项核心技能是将复杂性分解为可管理的块。即使是那些多年来一直使用Java编程的人,也要努力弄清楚你发布的代码中发生了什么。
进一步发展非常重要的另一项技能是了解标准库并尽可能使用它。这通常可以让您免于重新发明轮子。
根据以上3点,这是我的建议: