Skip to content

Latest commit

 

History

History
35 lines (27 loc) · 1.18 KB

判断文件最后一行是否包含换行符.md

File metadata and controls

35 lines (27 loc) · 1.18 KB

判断文件最后一行是否包含换行符

    public static void main(String[] args) {
        // File file = new File("E:\\Desktop\\测试换行符.txt");
        File file = new File("E:\\Desktop\\测试文件.txt");

        try {
            // 创建随机访问文件对象
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");

            // 定位到文件的倒数第二个字节
            long length = randomAccessFile.length();
            randomAccessFile.seek(length - 2);

            // 读取最后几个字节到缓冲区
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = randomAccessFile.read(buffer);

            // 判断最后一行是否包含换行符
            boolean lastLineContainsNewLine = false;
            if (bytesRead > 0) {
                String lastBytes = new String(buffer, 0, bytesRead);
                lastLineContainsNewLine = lastBytes.contains("\n");
            }

            randomAccessFile.close();

            System.out.println("最后一行是否包含换行符: " + lastLineContainsNewLine);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }