Java 如何将文件从一个位置复制到另一个位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16433915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy file from one location to another location?
提问by vijayk
I want to copy a file from one location to another location in Java. What is the best way to do this?
我想将文件从一个位置复制到 Java 中的另一个位置。做这个的最好方式是什么?
Here is what I have so far:
这是我到目前为止所拥有的:
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
public static void main(String[] args) {
File f = new File(
"D:\CBSE_Demo\Demo_original\fscommand\contentplayer\config");
List<String>temp=new ArrayList<String>();
temp.add(0, "N33");
temp.add(1, "N1417");
temp.add(2, "N331");
File[] matchingFiles = null;
for(final String temp1: temp){
matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(temp1);
}
});
System.out.println("size>>--"+matchingFiles.length);
}
}
}
This does not copy the file, what is the best way to do this?
这不会复制文件,这样做的最佳方法是什么?
采纳答案by Menno
You can use this(or any variant):
您可以使用此(或任何变体):
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Also, I'd recommend using File.separator
or /
instead of \\
to make it compliant across multiple OS, question/answer on this available here.
此外,我建议使用File.separator
或/
代替\\
使其在多个操作系统中兼容,此处提供有关此问题的问题/答案。
Since you're not sure how to temporarily store files, take a look at ArrayList
:
由于您不确定如何临时存储文件,请查看ArrayList
:
List<File> files = new ArrayList();
files.add(foundFile);
To move a List
of files into a single directory:
将一个List
文件移动到一个目录中:
List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
Files.copy(file.toPath(),
(new File(path + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
回答by Quamber Ali
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
回答by Amimo Benja
Use the New Java File classes in Java >=7.
在 Java >=7 中使用 New Java File 类。
Create the below method and import the necessary libs.
创建以下方法并导入必要的库。
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
Use the created method as below within main:
在 main 中使用如下创建的方法:
File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);
try {
copyFile(dirFrom, dirTo);
} catch (IOException ex) {
Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}
NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.
注意:- fileFrom 是您要复制到不同文件夹中的新文件 fileTo 的文件。
Credits - @Scott: Standard concise way to copy a file in Java?
积分 - @Scott:在 Java 中复制文件的标准简洁方法?
回答by Alexander Sidikov Pfeif
Using Stream
使用流
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
Using Channel
使用频道
private static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}
Using Apache Commons IO lib:
使用 Apache Commons IO 库:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
Using Java SE 7 Files class:
使用 Java SE 7 Files 类:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Performance test:
性能测试:
File source = new File("/Users/pankaj/tmp/source.avi");
File dest = new File("/Users/pankaj/tmp/dest.avi");
//copy file conventional way using Stream
long start = System.nanoTime();
copyFileUsingStream(source, dest);
System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
//copy files using java.nio FileChannel
source = new File("/Users/pankaj/tmp/sourceChannel.avi");
dest = new File("/Users/pankaj/tmp/destChannel.avi");
start = System.nanoTime();
copyFileUsingChannel(source, dest);
System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
//copy files using apache commons io
source = new File("/Users/pankaj/tmp/sourceApache.avi");
dest = new File("/Users/pankaj/tmp/destApache.avi");
start = System.nanoTime();
copyFileUsingApacheCommonsIO(source, dest);
System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
//using Java 7 Files class
source = new File("/Users/pankaj/tmp/sourceJava7.avi");
dest = new File("/Users/pankaj/tmp/destJava7.avi");
start = System.nanoTime();
copyFileUsingJava7Files(source, dest);
System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));
RESULTS:
结果:
Time taken by Stream Copy = 44,582,575,000
Time taken by Channel Copy = 104,138,195,000
Time taken by Apache Commons IO Copy = 108,396,714,000
Time taken by Java7 Files Copy = 89,061,578,000
回答by Shinwar ismail
Files.exists()
Files.exists()
Files.createDirectory()
Files.createDirectory()
Files.copy()
文件.copy()
Overwriting Existing Files: Files.move()
覆盖现有文件: Files.move()
Files.delete()
文件.delete()
Files.walkFileTree() enter link description here
Files.walkFileTree() 在此处输入链接描述
回答by S.Sarkar
Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException
this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
将文件从一个位置复制到另一个位置意味着需要将整个内容复制到另一个位置。Files.copy(Path source, Path target, CopyOption... options) throws IOException
此方法期望源位置是原始文件位置,目标位置是目标位置相同类型文件(与原始文件相同)的新文件夹位置。要么目标位置需要存在于我们的系统中,否则我们需要创建一个文件夹位置,然后在该文件夹位置我们需要创建一个与原始文件名同名的文件。然后使用复制功能,我们可以轻松地从一个位置复制文件到其他。
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}