【发布时间】:2016-11-14 17:26:40
【问题描述】:
我正在尝试从我的 java 目录接收文件,收集文档中的所有单词,将所有单词放入 TreeSet,然后打印出整个单词 TreeSet。当我尝试该程序时,从控制台中的TreeSet 打印出来的所有内容都是
Input file:
trees.docx
[]
它只是以这些空括号结束。注意:trees.docx 文件中只有单词“trees and stuff”。这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class CountWords {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Input file: ");
String fileName = sc.next();
File inputFile = new File(fileName);
Scanner in = new Scanner(inputFile);
Set<String> words = new TreeSet<String>();
// only happens if there is a next string
while(in.hasNext()){
words.add(in.next()); //adds this string to the treeSet initialized above
}
System.out.println(words); // prints the treeSet
}
}
【问题讨论】:
-
Java 无法真正将 docx 文件作为纯文本读取...
-
如果你想阅读微软文件,你需要使用像
Apache POI这样的库 -
非常感谢!我在我的电脑上用 .txt 文件尝试过这个,它完美无缺。