【发布时间】:2016-04-11 20:43:00
【问题描述】:
我在将文件读入 char 数组,然后将每个 char 与随机字母进行比较时遇到问题,比如说“e”。
到目前为止,这是我的代码,我认为 cbuf 为空,但我不明白,我认为这应该将文件的内容读入其中。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.CharBuffer;
public class CountCharacter {
public static void main(String[] args) {
FileReader fr = null;
int c;
int countOfLetter = 0;
try {
fr = new FileReader("C:\\Users\\User\\Desktop\\text.txt");
CharBuffer cbuf = null;
fr.read(cbuf);
for (int i = 0; i < cbuf.length(); i++) {
if (cbuf.charAt(i) == 'e')
countOfLetter++;
}
System.out
.println("The number of times 'e' occurred in this file is: "
+ countOfLetter);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
【问题讨论】:
标签: java filereader