java刪除文本文件最后一行為NUL的字符


有段代碼,如果文件末尾有一串NUL,就會報錯

因此想去掉NUL,再使用工具解析

NUL即ascii碼值為0的比特

public static void delNulAtLastLine(String fileName)
            throws Exception {
        RandomAccessFile file = new RandomAccessFile(fileName, "rw");
        long len = file.length();
        long start = file.getFilePointer();
        long nextend = start + len - 1;
        int i = -1;
        // 移動指針
        file.seek(nextend);
        byte[] buf = new byte[1];
        boolean isDelete = true;
        while (nextend > start) {
            i = file.read(buf, 0, 1);
            if(buf[0]==0){
                isDelete = true;
            }
            if (buf[0] == '\r') {
                // 刪除最后一行
                if(isDelete){
                    file.setLength(nextend - start);
                }
                break;
            }
            nextend--;
            file.seek(nextend);
        }
        file.close();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM