資策會|JAVA|FileReader 與 BufferedReader 差異
StackOeverFlow 是個好地方
以下有一個問題...
給你一篇文章,然後利用 FileReader 與 BufferedReader 來分別得到bytes, chars,line 各為多少!
這邊我煩惱了許久,於是上網發問啦!
What's different between using FileReader() and BufferedReader() to get the char? [duplicate]
我的疑問是在於 BufferedReader.readline 會自己吃掉換行字元 \n 那為何只得到10個,與21相去甚遠
解決的程式碼如下 :
public static void workWithFileReader() {
int i;
long len; //
int countChar = 0; //每讀到一個byte +1
int countLine = 0; //每讀到一個換行 char(10) +1
int lineTerminators = 0;
File file = new File("C:\\Users\\USER\\Downloads\\Sample.txt");
len=file.length();
try {
FileReader fr = new FileReader(file);
while((i=fr.read()) != -1) {
System.out.print((char)i);
countChar++;
if((char) i == 10) {
countLine++;
lineTerminators++;
}
if((char) i == 13) {
countLine++;
lineTerminators++;
}
}
System.out.println("----------------------");
System.out.println("共有"+len+"個位元組");
System.out.println("共有"+countChar+"個字元");
System.out.println("共有"+countLine+"列資料");
System.out.println(lineTerminators);
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
留言
張貼留言