Java-文件合并,文件追加
因为有人问怎么写,就写了个demo,亲测可用
@Test
public void appendFile() throws IOException {
File fileout = new File("/www.cnblogs.com/tomcatandjerry/abc1.txt");
try (
RandomAccessFile raf = new RandomAccessFile(fileout, "rw");
//这里分开写,不要FileChannel fc = new FileInputStream().getChannel(),这样只会关闭fc,但是FileInputStream没有关闭
FileInputStream fis = new FileInputStream("/www.cnblogs.com/tomcatandjerry/abc.txt");
FileChannel fc2 = fis.getChannel();
) {
raf.seek(raf.length());//移动位置到文件末,这样后面追加数据就不会覆盖原来的内容
fc2.transferTo(0, fis.available(), raf.getChannel());
}
}
使用jdk7的try with resource语法,让代码看上去精简一些
posted on 2019-12-12 16:59 tomcat and jerry 阅读(435) 评论(0) 收藏 举报
浙公网安备 33010602011771号