Java-将文件复制到新文件或现有文件
我想写一个函数副本(文件f1,文件f2) f1始终是一个文件。 f2是文件或目录 如果f2是一个目录,我想将f1复制到此目录(文件名应保持不变) 如果f2是一个文件,我想将f1的内容复制到文件f2的末尾 例如,如果F2具有以下内容: 22222222 F1有内容 1111111111111 我复制(f1,f2),那么f2应该变成 22222222 1111111111111Java-将文件复制到新文件或现有文件,java,file,Java,File,我想写一个函数副本(文件f1,文件f2) f1始终是一个文件。 f2是文件或目录 如果f2是一个目录,我想将f1复制到此目录(文件名应保持不变) 如果f2是一个文件,我想将f1的内容复制到文件f2的末尾 例如,如果F2具有以下内容: 22222222 F1有内容 1111111111111 我复制(f1,f2),那么f2应该变成 22222222 1111111111111 谢谢 查看下面的链接。它是使用NIO将一个文件复制到另一个文件的源文件 FileOutputStream有一个构造函数,允
谢谢 查看下面的链接。它是使用NIO将一个文件复制到另一个文件的源文件
FileOutputStream有一个构造函数,允许您指定附加而不是覆盖 可以使用此选项将f1的内容复制到f2的末尾,如下所示:
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2, true);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
扩大艾伦的职位:
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);
}
使用Commons IO可以简化大量的流式grunt工作。使用Allain Lolande答案中的代码并对其进行扩展,这应该解决问题的两个部分:
File f1 = new File(srFile);
File f2 = new File(dtFile);
// Determine if a new file should be created in the target directory,
// or if this is an existing file that should be appended to.
boolean append;
if (f2.isDirectory()) {
f2 = new File(f2, f1.getName());
// Do not append to the file. Create it in the directory,
// or overwrite if it exists in that directory.
// Change this logic to suite your requirements.
append = false;
} else {
// The target is (likely) a file. Attempt to append to it.
append = true;
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(f1);
out = new FileOutputStream(f2, append);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
我认为拷贝的文件版本应该被称为
append
,我们可以使用in.skip(srOffset)
和totalTobeCopied
来管理srFile
中的START
和END
。但是有没有一种方法可以从一个特定的偏移量开始复制到dtFile,即控制dtFile
的START
和END
?Files.copyTo(新文件(“/inputpath”).toPath(),新文件outputstream(新文件(/outputpath”),true))
可以从Java 7运行