【发布时间】:2015-04-08 12:53:02
【问题描述】:
我有一个程序必须在文件中读取多个内容,例如文件中有多少元音等。出于测试目的,我刚刚将结果打印到控制台,但是我需要将其打印到单独的文件,所以我正在使用 Print Writer。我将包含我的整个代码,这样你就可以确切地看到它在做什么。
//Variables
int vowels = 0, digits = 0, spaces = 0, upperCase = 0, lowerCase = 0;
char ch;
// Creates File Chooser and Scans Selected file.
Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser("E:/OOSD/src/textAnalyser");
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
//Loops through the file until it has counted everything.
while (in.hasNext()) {
//Gets the next line from the input
String line = in.nextLine();
// loop goes on till it has no next line.
for (int i = 0; i < line.length(); i++) {
ch = line.charAt(i);
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i'
|| ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') {
vowels++;
} else if (Character.isDigit(ch)) {
digits++;
} else if (Character.isWhitespace(ch)) {
spaces++;
} else if (Character.isUpperCase(ch)) {
upperCase++;
} else if (Character.isLowerCase(ch)) {
lowerCase++;
}
}
}//Ends While Loop.
PrintWriter writer = new PrintWriter("Output.txt", "UTF-8");
writer.println("Vowels: " + vowels);
writer.println("Digits : " + digits);
writer.println("Spaces : " + spaces);
writer.println("Capital Letters : " + upperCase);
writer.println("LoweCase : " + lowerCase);
writer.close();
如果您能告诉我为什么它不会打印到指定的输出文件,那将非常感谢 :) 抱歉,这是一个很长的问题。
【问题讨论】:
-
它应该写入指定的文件。如果没有,你可能做错了什么。是否产生错误信息?您确定要在正确的目录中查找文件吗?
标签: java output printwriter