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;
}
在百万级别的数据文件,第一行插入文件头
最新推荐文章于 2023-11-28 10:58:09 发布