RandomAccessFile 读写文件

将目录下的N个日志文件读写到一个文件中。

@Test
void verification() throws Exception {
    File f = new File("D:\\Logs");
    String wPath = "D:\\\\Logs\\0.logsAll.log";
    File wf = new File(wPath);
    if (wf.exists()) {
        wf.delete();
    }
    RandomAccessFile writeFile = new RandomAccessFile(wPath, "rw");
    writeFile.seek(0); //可以设置偏移量,如果写完的数据再把它读出来时,需要设置这个偏移量
    for (File file : f.listFiles()) {
        if (file.isFile()) {
            RandomAccessFile readFile = new RandomAccessFile(file.getPath(), "r");
            byte[] buffer = new byte[1024];
            int hasRead = 0;
            while ((hasRead = readFile.read(buffer)) != -1) {
                writeFile.write(buffer, 0, hasRead);
            }
            readFile.close();
        }
    }
    logger.info("文件大小:{}", writeFile.length());
    writeFile.close();
}

 

posted @ 2022-05-10 11:14  VipSoft  阅读(294)  评论(0编辑  收藏  举报