1.小文件添加头部内容
代码实现:
package com.xtm.test;
import java.io.RandomAccessFile;
public class Main {
public static final String PATH = "F://a.txt";
public static void main(String[] args) throws Exception{
String header = "--文件头--";
appendFileHeader(header.getBytes(),PATH);
}
/**
* 向src文件添加header
* @param header
* @param srcPath
* @throws Exception
*/
private static void appendFileHeader(byte[] header,String srcPath) throws Exception{
RandomAccessFile src = new RandomAccessFile(srcPath, "rw");
int srcLength = (int)src.length() ;
byte[] buff = new byte[srcLength];
src.read(buff , 0, srcLength);
src.seek(0);
src.write(header);
src.seek(header.length);
src.write(buff);
src.close();
}
}
效果:
F盘文件a.txt 内容:aaa
执行程序后a.txt的内容:--文件头--aaa
2.大文件添加头部内容
代码实现:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* *@author TianMing.Xiong
*/
public class BigFileAddHead {
public static void main(String[] args){
// 将282兆的文件内容头部添加一行字符 "This is a head!"
String strHead = "This is a head!" ; // 添加的头部内容
String srcFilePath = "big_file" ; // 原文件路径
String destFilePath = "big_file_has_head" ; // 添加头部后文件路径 (最终添加头部生成的文件路径)
long startTime = System.currentTimeMillis();
try {
// 映射原文件到内存
RandomAccessFile srcRandomAccessFile = new RandomAccessFile(srcFilePath, "r");
FileChannel srcAccessFileChannel = srcRandomAccessFile.getChannel();
long srcLength = srcAccessFileChannel.size();
System.out.println("src file size:"+srcLength); // src file size:296354010
MappedByteBuffer srcMap = srcAccessFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, srcLength);
// 映射目标文件到内存
RandomAccessFile destRandomAccessFile = new RandomAccessFile(destFilePath, "rw");
FileChannel destAccessFileChannel = destRandomAccessFile.getChannel();
long destLength = srcLength + strHead.getBytes().length;
System.out.println("dest file size:"+destLength); // dest file size:296354025
MappedByteBuffer destMap = destAccessFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, destLength);
// 开始文件追加 : 先添加头部内容,再添加原来文件内容
destMap.position(0);
destMap.put(strHead.getBytes());
destMap.put(srcMap);
destAccessFileChannel.close();
System.out.println("dest real file size:"+new RandomAccessFile(destFilePath,"r").getChannel().size());
System.out.println("total time :" + (System.currentTimeMillis() - startTime));// 貌似时间不准确,异步操作?
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
控制台输出:
src file size:296354010
dest file size:296354025
dest real file size:296354025
total time :460
Process finished with exit code 0
效果:
添加头部前文件的内容:
%PDF-1.6
%����
4219 0 obj
<</Linearized 1/L 296347369/O 4221/E 241472/N 506/T 296342513/H [ 479 2168]>>
endobj
(内容太多省略)
添加头部后文件的内容:
This is a head!%PDF-1.6
%����
4219 0 obj
<</Linearized 1/L 296347369/O 4221/E 241472/N 506/T 296342513/H [ 479 2168]>>
endobj
(内容太多,省略)