首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java FileInputStream read() 判斷 -1 邏輯錯誤:分號導致迴圈空轉

     編輯:程式設計綜合問答

錯誤代碼

while((n=fis.read(bytes))!=-1); {  // <-- 這裡多了一個分號!
    String s = new String(bytes, 0, n);
    System.out.println(s);
}

問題解析

while(...); 後面的分號使得 while 迴圈體為空語句,實際執行流程:

  1. 迴圈不斷讀取直到返回 -1,n 最後為 -1。
  2. 迴圈結束後,執行大括號內的代碼塊(視為獨立區塊),但此時 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 作為長度構造字串,否則會包含緩衝區殘留資料。
  • Java 7+ 建議使用 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();
        }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved