package com.wondream.myframework.app.basictest.io; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileTest { Log logger = LogFactory.getLog(RandomAccessFileTest.class); @Test public void testWrite(){ RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile("./logs/data.txt", "rw"); long fileLength = randomAccessFile.length(); randomAccessFile.skipBytes((int)fileLength); int i = Integer.MAX_VALUE; randomAccessFile.write(i>>>24); randomAccessFile.write(i>>>16); randomAccessFile.write(i>>>8); randomAccessFile.write(i); String data = "hello123优秀"; randomAccessFile.write(data.getBytes()); fileLength = randomAccessFile.length(); logger.info(fileLength); } catch (Exception e) { e.printStackTrace(); } finally { if(randomAccessFile!=null){ try { randomAccessFile.close(); } catch (IOException e) { e.printStackTrace(); } randomAccessFile = null; } } } @Test public void testRead(){ RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile("./logs/data.txt", "rw"); int bufferLen = 1024*100; byte[] data = new byte[bufferLen]; while (randomAccessFile.read(data, 0, bufferLen)!=-1){ logger.info(new String(data, "UTF-8")); } } catch (Exception e){ e.printStackTrace(); } finally { if(randomAccessFile!=null){ try { randomAccessFile.close(); } catch (IOException e) { e.printStackTrace(); } randomAccessFile = null; } } } }
RandomAccessFile的基本使用
最新推荐文章于 2023-08-21 22:15:00 发布