記一次差點造成重大事故的文件讀寫

原本的代碼中是這樣的:

        String path = args[0];
        File file = new File(path);
        StringBuilder sb = new StringBuilder();
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            while ( fileInputStream.read(bytes) > 0) {
                sb.append(new String(bytes));
            }
        } catch (IOException e) {
            System.out.println("文件讀取異常");
            return;
        }

這個會有什麼問題呢?假如文件最後一次讀取長度不足1024,會在字符串的最後面拼空格。

改吧改吧:記錄讀到的長度,拼到後面

        String path = args[0];
        File file = new File(path);
        StringBuilder sb = new StringBuilder();
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int count = 0;
            while ((count = fileInputStream.read(bytes)) > 0) {
                sb.append(new String(bytes, 0, count));
            }
        } catch (IOException e) {
            System.out.println("文件讀取異常");
            return;
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章