RandomAccessFile 工具类操作文件内容

背景

需求要读取xml文件第一行识别文件类型,识别完文件类型后删除第一行数据然后对xml文件进行解析。

主要是文件内容操作,用BufferedReader 的readLine()就可以轻松完成读取第一行操作。但是要删除内容就很难,百度后发现,基于原始文件流操作来说,只能从第二行开始读,然后再把读出来的数据覆盖原文件这样操作。后来发现RandomAccessFile类可以相对比较轻松的完成对文件的一些操作(虽然也不是完全封装),参考网上一些已经写好的相关操作工具,收集整理方便以后用。


@Slf4j
public class OperateFileContentsUtil {

    /**
     * @throws
     * @Title: removeFileLine
     * @Description: TODO(该方法为从文件开头删除前n行)
     * @param: @param file 文件
     * @param: @param lineNum 删除的行行数
     * @param: @throws IOException
     * @return: void
     */
    public static void removeFileLine(File file, int lineNum) throws IOException {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "rw");
            // Initial write position.
            // 写文件的位置标记,从文件开头开始,后续读取文件内容从该标记开始
            long writePosition = raf.getFilePointer();
            for (int i = 0; i < lineNum; i++) {
                String line = raf.readLine();
                if (line == null) {
                    break;
                }
            }
            // Shift the next lines upwards.
            // 读文件的位置标记,写完之后回到该标记继续读该行
            long readPosition = raf.getFilePointer();

            // 利用两个标记,
            byte[] buff = new byte[1024];
            int n;
            while (-1 != (n = raf.read(buff))) {
                raf.seek(writePosition);
                raf.write(buff, 0, n);
                readPosition += n;
                writePosition += n;
                raf.seek(readPosition);
            }
            raf.setLength(writePosition);
        } catch (IOException e) {
            log.error("readAndRemoveFirstLines error", e);
            throw e;
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                log.error("close RandomAccessFile error", e);
                throw e;
            }
        }
    }


    /**
     * @throws
     * @Title: appendContentToFile
     * @Description: TODO(在文件末尾追加内容)
     * @param: @param file
     * @param: @param content
     * @param: @throws IOException
     * @return: void
     */
    public static void appendContentToFile(File file, String content) throws IOException {
        RandomAccessFile randomFile = null;
        try {
            // 打开一个随机访问文件流,按读写方式
            randomFile = new RandomAccessFile(file, "rw");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                randomFile.close();
                randomFile = null;
            }
        }
    }


    /**
     * @throws
     * @Title: checkFileInSize
     * @Description: TODO(检查文件字节数是否超出限制)
     * @param: @param file
     * @param: @param limitSize
     * @param: @return
     * @return: boolean
     */
    private static boolean checkFileInSize(File file, Long limitSize) {
        return file.length() <= limitSize;
    }

    public static void main(String[] args) throws IOException {
//        removeFileLine(new File("/Users/qingshan/Desktop/xixi.xml"), 1);
//        appendContentToFile(new File("/Users/qingshan/Desktop/xixi.xml"), "haha");
        System.out.println(checkFileInSize(new File("/Users/qingshan/Desktop/xixi.xml"), 100L));
    }
}

参考:

https://blog.csdn.net/weixin_38860565/article/details/89494539

猜你喜欢

转载自www.cnblogs.com/qingshan-tang/p/12518227.html