FileReader "eats" 每个首字母
FileReader "eats" each first letter
我有一个代码:
File readFile = new File("acc\10001.txt");
protected void readData(File file){
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
while(reader.read() != -1){
System.out.println(reader.readLine());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
方法在 Main class 的构造函数中。启动项目时,控制台显示(例如):“est”而不是“Test”,“0001”而不是“10001”。
它适用于所有字符串和整数。
感谢您的帮助。
您的代码段:
while(reader.read() != -1){
System.out.println(reader.readLine());
}
每次计算 while 条件时读取一个字符(read()
被调用并且 it reads next character.
用更好的方法更改代码:
String line="";
while ((line=reader.readLine()) != null) { //variable line gets assigned with value and then it's checked against null
System.out.println(line);
}
我有一个代码:
File readFile = new File("acc\10001.txt");
protected void readData(File file){
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
while(reader.read() != -1){
System.out.println(reader.readLine());
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
方法在 Main class 的构造函数中。启动项目时,控制台显示(例如):“est”而不是“Test”,“0001”而不是“10001”。
它适用于所有字符串和整数。
感谢您的帮助。
您的代码段:
while(reader.read() != -1){
System.out.println(reader.readLine());
}
每次计算 while 条件时读取一个字符(read()
被调用并且 it reads next character.
用更好的方法更改代码:
String line="";
while ((line=reader.readLine()) != null) { //variable line gets assigned with value and then it's checked against null
System.out.println(line);
}