while((n=fis.read(bytes))!=-1); { // <-- 這裡多了一個分號!
String s = new String(bytes, 0, n);
System.out.println(s);
}
while(...); 後面的分號使得 while 迴圈體為空語句,實際執行流程:
n 最後為 -1。n == -1,new String(bytes, 0, -1) 拋出 StringIndexOutOfBoundsException。int n;
while ((n = fis.read(bytes)) != -1) { // 無分號!
String s = new String(bytes, 0, n);
System.out.println(s);
}
read(byte[]) 返回實際讀取的位元組數,末尾返回 -1。n 作為長度構造字串,否則會包含緩衝區殘留資料。try-with-resources 自動關閉流。import java.io.*;
public class ReadFileDemo {
public static void main(String[] args) {
File file = new File("f:/bb.txt");
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}