zoukankan      html  css  js  c++  java
  • RandomAccessFile操作文件

     1 package file;
     2 
     3 import java.io.File; 
     4 import java.io.FileInputStream;
     5 import java.io.FileOutputStream;
     6 import java.io.IOException;
     7 import java.io.RandomAccessFile;
     8 
     9 
    10 public class InsertContent {
    11 
    12     public static void insert(String fileName,long pos,String insertContent) throws IOException{
    13         File tmp = File.createTempFile("tmp", null);
    14         tmp.deleteOnExit();
    15         try(
    16             RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
    17             FileOutputStream tmpOut = new FileOutputStream(tmp);
    18             FileInputStream tmpInputStream = new FileInputStream(tmp)
    19             ){
    20             //  将记录指针移动文件末尾  追加内容
    21 //            raf.seek(raf.length());
    22             
    23             // 将记录指针移动指定位置
    24             raf.seek(pos);
    25             
    26             byte[] bbuf = new byte[64];
    27         
    28             int hasRead = 0;
    29             
    30             StringBuffer sbf = new StringBuffer();
    31             
    32             while((hasRead = raf.read(bbuf)) > 0 ){
    33                 tmpOut.write(bbuf, 0 , hasRead);
    34                 sbf.append(new String(bbuf));
    35             }
    36             System.out.println(sbf.toString());
    37             
    38             raf.seek(pos);
    39             
    40             raf.write(insertContent.getBytes());
    41             
    42             while ((hasRead = tmpInputStream.read(bbuf)) > 0) {
    43                 raf.write(bbuf , 0 , hasRead);
    44             }
    45         }
    46     }
    47     
    48     public static void main(String[] args) {
    49         try {
    50             insert("f:/new 1.txt", 45, "ajsdkjfksldjfkl");
    51         } catch (IOException e) {
    52             e.printStackTrace();
    53         }
    54     }
    55 }
  • 相关阅读:
    centos 7.5 snmp 安装
    centos 7.5 telnet 离线安装
    使用httpClient发送请求(支持https)
    kafka基本概念
    List根据时间字符串排序
    mac安装yosys遇到`dyld: malformed mach-o image`报错
    ctags的--exclude选项
    每周分享(3)
    实践OKR极易出现的四大误区
    从OKR小白到成功落地OKR(三)
  • 原文地址:https://www.cnblogs.com/zfy0098/p/5241078.html
Copyright © 2011-2022 走看看