我很好奇我是否(正确)从此文件中读取文本。
目的:从文件中读取文本并将其放入名为“lines”的集合中(该集合是 LinkedHashSet,因为我应该按照元素添加的顺序对元素进行排序)。
这是 main() 函数的代码(省略导入):
public class Main {
public static void main(String[] args) {
try {
Set<FileExaminer> examiners = new LinkedHashSet<>();
examiners.add(new FileExaminer("raven.txt"));
examiners.add(new FileExaminer("jabberwocky.txt"));
for (FileExaminer fe : examiners) {
System.out.println("-----------------------");
fe.display(45);
System.out.println();
fe.displayCharCountAlpha();
fe.displayCharCountNumericDescending();
}
}catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
}
}
这是 LinkedHashSet 的创建:
private LinkedHashSet< String > lines = new LinkedHashSet<>();
以下是此处引用的 FileExaminer 类的代码:
public FileExaminer(String filename) throws FileNotFoundException {
File file = new File(file);
if(file.exists()){
Scanner reader = new Scanner(filename);
/** Read the contents of the file and place them into the lines set */
while( reader.hasNext() ){
lines.add( reader.next() );
} // end of while
reader.close();
} // end of if
else{
/** Throw exception if the file does not exist */
throw new FileNotFoundException("File not found: " + filename);
} // end of else
/** Call calculateCharCountAlpha */
calculateCharCountAlpha();
} // end of constructor
我遇到的问题在于程序的输出。 当我从“行”集中打印出所需的行时,我会获取文件名,当我从其他方法打印出其他集中的项目时,它可以正常工作,但它正在分析文件名,而不是其中的文本文件。 我不确定为什么会出现这种情况。
我已经在上一个问题中发布了 displayCharCountAlpha 的代码(发现它工作正常),所以我不会包含它。
displayCharCountAlpha():
public void displayCharCountAlpha(){ // prints out charCountAlpha
System.out.println(charCountAlpha);
}
displayCharCountNumericDescending():
public void displayCharCountNumericDescending() { // prints out charCountNumericDescending
System.out.println(charCountNumericDescending);
}
显示():
public void display(int numberOfLines){
int count = 0; // control-variable that can be checked throughout iteration
for(String s : lines){
System.out.println(s);
count++;
if(count == numberOfLines-1){ // number of lines insinuates that the loop has the set amount of times
break; // break out of the loop
} // end of if
} // end of for
} // end of Display()
最佳答案
简单的错误,
Scanner reader = new Scanner(filename);
应该是
Scanner reader = new Scanner(file);
当前,您从 String
filename
读取(并且您想从 File
file
读取) .
关于Java - 我是否正确地读取了该文件中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44250380/