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(); }
本文来自博客园,作者:VipSoft 转载请注明原文链接:https://www.cnblogs.com/vipsoft/p/16252698.html