在百万级别的数据文件,第一行插入文件头

public static void main(String[] args) throws IOException {
    String headValue = "01|C1081621000014|" + 2020 + "|" + 1;//自定义的文件头
    String zxgyingyongfilepath = "D:/rjcwg/sftpfile/ferc/";//数据文件存放路径
    String lastfilename = "C1081621000014_M7_N_20200322_00000007.TXT";//数据文件名称
    writeFileHeader(headValue, new File(zxgyingyongfilepath + lastfilename));
    System.out.println("生成成功!!!!");
}

/**
 * 报文插入文件头
 * @param content   插入文件头内容
 * @param file      报文文件
 * @return
 * @throws IOException
 */
public static boolean writeFileHeader(String content, File file) throws IOException {
    System.out.println("文件头"+content);
    System.out.println("文件名"+file.getName());
    // 1.读取txt文件,然后在第一行加上文件头信息
    File tmp = File.createTempFile("tmp", null);
    FileOutputStream tmpOut = new FileOutputStream(tmp);
    FileInputStream tmpIn = new FileInputStream(tmp);
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(file, "rw");
        byte[] buf = new byte[64];
        int hasRead = 0;
        while ((hasRead = raf.read(buf)) > 0) {
            // 把原有内容读入临时文件
            tmpOut.write(buf, 0, hasRead);
        }
        raf.seek(0L);
        raf.write(content.getBytes());
        raf.write("\r\n".getBytes());

        // 追加临时文件内容
        while ((hasRead = tmpIn.read(buf)) > 0) {
            raf.write(buf, 0, hasRead);
        }
        System.out.println("====================添加文件头结束=================");
    } catch (IOException e) {
        System.out.println("写入失败!");
        e.printStackTrace();
        return false;
    } finally {
        try {
            raf.close();
            tmpIn.close();
            tmpOut.close();
        } catch (IOException e) {
            System.out.println("写入失败,关闭流失败!");
            e.printStackTrace();
            return false;
        }
    }
    return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值