记一次差点造成重大事故的文件读写

原本的代码中是这样的:

        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;
        }

 

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