使用RandomAccessFile类读取和重写最后一行

您所在的位置:网站首页 java删除文件最后一行 使用RandomAccessFile类读取和重写最后一行

使用RandomAccessFile类读取和重写最后一行

2023-03-22 23:06| 来源: 网络整理| 查看: 265

RandomAccessFile类支持“随机访问”方式,可以跳转到文件的任意位置处读写数据

RandomAccessFile对象类有个位置指示器,指向当前读写处的位置,当前读写n个字节后,文件指示器将指向这n个字节后面的下一个字节处

“r”:以只读的方式打开,调用该对象的任何write(写)方法都会导致IOException异常 “rw”:以读、写方式打开,支持文件的读取或写入。若文件不存在,则创建 “rws”:以读、写方式打开,与“rw”不同的是,还要对文件内容的每次更新都同步更新到潜在的存储设备中去。s表示synchronous同步 “rwd”:以读、写方式打开,与“rw”不同的是,还要对文件内容的每次更新都同步更新到潜在的存储设备中去。使用“rwd”模式仅要求将文件的内容更新到存储设备中,而使用“rws”模式除了更新文件的内容,还要更新文件的元数据(metadata),因此至少要求1次低级别的I/O操作

eg:

 读取最后一行 、重写最后一行

import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.ArrayList; public class ReadLastLine { public static void main(String[] args) throws Exception { String fileName = "E:\\test.txt"; long start = System.currentTimeMillis(); String lastLine = readEndLine(fileName); long delt = System.currentTimeMillis() - start; System.out.println(lastLine); System.out.println("读取时间(毫秒):" + delt); ///////////////////////////////////////////////////// start = System.currentTimeMillis(); rewriteEndLine(fileName,"1234567890"); delt = System.currentTimeMillis() - start; System.out.println("更新时间(毫秒):" + delt); } public static void writeEndLine(String fileName, String string) throws Exception { RandomAccessFile file = new RandomAccessFile(fileName, "rw"); long len = file.length(); long start = file.getFilePointer(); long nextend = start + len - 1; byte[] buf = new byte[1]; file.seek(nextend); file.read(buf, 0, 1); if (buf[0] == '\n') file.writeBytes(string); else file.writeBytes("\r\n" + string); file.close(); } public static void rewriteEndLine(String fileName,String newStr) throws Exception { RandomAccessFile file = new RandomAccessFile(fileName, "rw"); long len = file.length(); long start = file.getFilePointer(); long nextend = start + len - 1; System.out.println(nextend); int i = -1; // 移动指针 file.seek(nextend); byte[] buf = new byte[1]; while (nextend > start) { i = file.read(buf, 0, 1); if (buf[0] == '\r') { // 删除最后一行 file.setLength(nextend - start); break; } nextend--; file.seek(nextend); } file.close();     writeEndLine(fileName,newStr); } public static String readEndLine(String fileName) throws Exception { RandomAccessFile file = new RandomAccessFile(fileName, "rw"); long start = file.getFilePointer(); long len = file.length(); long nextend = start + len - 1; file.seek(nextend); byte buf[] = new byte[1]; int i = -1; String linestr = null; while (nextend > start) { i = file.read(buf, 0, 1); if (buf[0] == '\n') { if ((linestr = file.readLine()) != null) { System.out.println("endline:" + linestr); break; } } nextend--; file.seek(nextend); } file.close(); return linestr; } }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3