【发布时间】:2021-07-07 03:33:17
【问题描述】:
我正在处理一个需要我导入文本文件、读取文件并以不同方式对单词进行排序(即升序、唯一单词等)的项目。到目前为止,我已经能够导入文件并打印它,直到我添加了将列表排序为行和单词的命令。
我使用缓冲读取器来存储行和单词,但在执行时,我不知道数据是否已存储在单独的数组列表中,并且控制台不会打印存储的单词数在 ArrayList wordList 中。
我哪里错了?
到目前为止,这是我的代码:
public static void main(String[] args)throws IOException{
if(args.length == 0){
System.out.println("Error, usage: java ClassName inputfile");
System.exit(1);
}
File randomText = new File(args[0]);
if(randomText.exists() && randomText.isFile()){
processFile(randomText);
} else{
System.err.println("ERROR: file does not exist");
System.exit(1);
}
}
public static void processFile(File randomText)throws IOException, FileNotFoundException{
ArrayList<String> lineList = new ArrayList<String>();
ArrayList<String> wordList = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(randomText));
StringBuffer sb = new StringBuffer();
String line;
while((line=br.readLine()) != null){
sb.append(line);
sb.append("\n");
lineList.add(line);
}
while((line = br.readLine()) != null){
wordList = new ArrayList<String>(Arrays.asList(line.split(" |.")));
}
System.out.println("Total number of words in the file: " + wordList.size());
br.close();
}
【问题讨论】:
-
文件阅读器(尤其是
BufferedReader,在您的情况下)按顺序读取文件一次。一旦你读过它,它就消失了。您需要返回文件的开头或遍历lines数组以拆分为单词。 -
您能否发布(至少部分)文本文件,以便我可以根据您的实际数据测试我的代码?文件是否只包含 ASCII 字符?
标签: java string arraylist bufferedreader