我尝试用char读取一个File char。不幸的是,Java在从文件中读取字符时会忽略EOF。
FileReader fileReader = new FileReader(fileText);
char c;
String word = "";
List<String> words = new ArrayList<String>();
while ((c = (char) fileReader.read()) != -1) {
System.out.println(c);
if (c != ' ') {
word = word + c;
}
else {
words.add(word + " ");
word = "";
}
}
在读取文件后应该分解,但它永远不会停止运行....
答案 0 :(得分:8)
在Java中,char
是无符号的,不能等于-1
。你应该在进行演员表之前进行比较。
int ch;
while ((ch = fileReader.read()) != -1) {
char c = (char)ch;
System.out.println(c);
...
}
答案 1 :(得分:4)
这是因为char
不能等于-1
,即使您为其分配了-1
:
char c = (char)-1;
System.out.println(c == -1); // prints false
将c
设为int
,仅在连接时将其投放到char
:
word = word + (char)c;
更好的是,使用StringBuilder
在运行时构建字符串:否则,在循环中创建大量临时字符串对象,这些对象将被丢弃。
StringBuilder word = new StringBuilder();
List<String> words = new ArrayList<String>();
int c;
while ((c = fileReader.read()) != -1) {
System.out.println((char)c);
word.append((char)c);
if (c == ' ') {
words.add(word.toString());
word = new StringBuilder();
}
}
答案 2 :(得分:2)
您应该尝试以下代码
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader(fileLocation);
int c;
String word = "";
List<String> words = new ArrayList<String>();
while ((c = (int) fileReader.read()) != -1) {
System.out.println((char)c);
char ch = (char)c;
if (ch != ' ') {
word = word + ch;
} else {
words.add(word + " ");
word = "";
}
}
System.out.println(word);
}