Java 在不同位置复制和重命名文件
我有一个文件example.tar.gz,我需要用不同的名称将它复制到另一个位置 示例\u test.tar.gz。我试过了Java 在不同位置复制和重命名文件,java,Java,我有一个文件example.tar.gz,我需要用不同的名称将它复制到另一个位置 示例\u test.tar.gz。我试过了 private void copyFile(File srcFile, File destFile) throws IOException { InputStream oInStream = new FileInputStream(srcFile); OutputStream oOutStream = new FileOutputStream(destF
private void copyFile(File srcFile, File destFile) throws IOException {
InputStream oInStream = new FileInputStream(srcFile);
OutputStream oOutStream = new FileOutputStream(destFile);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream(oInStream);
while((nLength = oBuffInputStream.read(oBytes)) > 0) {
oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
}
在哪里
String from_path = new File("example.tar.gz");
File source = new File(from_path);
File destination = new File("/temp/example_test.tar.gz");
if(!destination.exists())
destination.createNewFile();
然后
copyFile(source, destination);
它不起作用。这条路是正确的。它打印文件是否存在。有人能帮我吗?为什么要重新发明轮子,只要使用,这将为您处理许多情况
I would suggest Apache commons FileUtils or NIO (direct OS calls)
或者只是这个 归功于乔希-
更新: 已从@bestss更改为transferTo
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new RandomAccessFile(sourceFile,"rw").getChannel();
destination = new RandomAccessFile(destFile,"rw").getChannel();
long position = 0;
long count = source.size();
source.transferTo(position, count, destination);
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
包
java.nio.file
中有Files
类。您可以使用copy
方法
示例:Files.copy(sourcePath,targetPath)
用文件的新名称创建一个targetPath对象(它是
Path
的一个实例)。在关闭它之前尝试flush()
你的流。在文章中更正此代码:字符串from_Path=new file(“example.tar.gz”)
@Mohamed,关闭前不需要刷新您不需要使用带有FileOutputStream的createNewFile,也不应该使用BufferedInputStream(),这并没有真正的帮助。只需使用大于1k的字节[]oBytes。最后但并非最不重要的一点是,FileChannel.transferTo
是复制文件的最佳方式使用FileStreams复制文件可能效率低下,请查看java.nio.channels.FileChannel.transferTo
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new RandomAccessFile(sourceFile,"rw").getChannel();
destination = new RandomAccessFile(destFile,"rw").getChannel();
long position = 0;
long count = source.size();
source.transferTo(position, count, destination);
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}