Java-将文件复制到新文件或现有文件 [英] Java- Copy file to either new file or existing file

查看:88
本文介绍了Java-将文件复制到新文件或现有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数副本(文件f1,文件f2)
f1总是一个文件。
f2是一个文件或目录。

如果f2是一个目录,我想将f1复制到这个目录中(文件名应该保持不变)。

如果f2是一个文件,我想将f1的内容复制到文件f2的末尾。


$ b $因此,例如,如果F2有内容:


2222222222222




和F1有内容


1111111111111


然后我复制(f1,f2)然后f2应该变成b
$ b


2222222222222



1111111111111

感谢!

解决方案

Apache Commons IO的救援!



在Allain的帖子上展开:

 档案f1 =新档案(srFile); 
文件f2 =新文件(dtFile);

InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2,true); //追加输出流

try {
IOUtils.copy(in,out);
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);





$ b

使用Commons IO可以简化大量的流程工作。 >

I would like to write a function copy(File f1, File f2) f1 is always a file. f2 is either a file or a directory.

If f2 is a directory I would like to copy f1 to this directory (the file name should stay the same).

If f2 is a file I would like to copy the contents of f1 to the end of the file f2.

So for example if F2 has the contents:

2222222222222

And F1 has the contents

1111111111111

And I do copy(f1,f2) then f2 should become

2222222222222

1111111111111

Thanks!

解决方案

Apache Commons IO to the rescue!

Expanding on Allain's post:

  File f1 = new File(srFile);
  File f2 = new File(dtFile);

  InputStream in = new FileInputStream(f1);
  OutputStream out = new FileOutputStream(f2, true); // appending output stream

  try {
     IOUtils.copy(in, out);
  }
  finally {
      IOUtils.closeQuietly(in);
      IOUtils.closeQuietly(out);
  }

Using Commons IO can simplify a lot of the stream grunt work.

这篇关于Java-将文件复制到新文件或现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆