Как скопировать файл из одного места в другое?
Я хочу скопировать файл из одного места в другое место на Java. Каков наилучший способ сделать это?
Вот что у меня так далеко:
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);
}
}
}
Это не копирует файл, каков наилучший способ сделать это?
Ответы
Ответ 1
Вы можете использовать this (или любой вариант):
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Кроме того, я рекомендую использовать File.separator
или /
вместо \\
, чтобы он совместим с несколькими ОС, вопрос/ответ на этот доступный здесь.
Поскольку вы не знаете, как временно хранить файлы, посмотрите ArrayList
:
List<File> files = new ArrayList();
files.add(foundFile);
Переместить файлы 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);
}
Ответ 2
Использование 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();
}
}
Использование канала
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();
}
}
Использование Apache Commons IO lib:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
Используя класс Java SE 7 Files:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Тест производительности:
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));
РЕЗУЛЬТАТЫ:
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
Ответ 3
Используйте классы New Java File в Java >= 7.
Создайте приведенный ниже метод и импортируйте необходимые библиотеки.
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
Используйте созданный метод, как показано ниже:
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 - это файл, который вы хотите скопировать в новый файл fileTo в другой папке.
Кредиты - @Scott: Стандартный сжатый способ копирования файла на Java?
Ответ 4
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() );
}
}
Ответ 5
Files.exists()
Files.createDirectory()
Files.copy()
Перезапись существующих файлов: Files.move()
Files.delete()
Files.walkFileTree() введите описание ссылки здесь
Ответ 6
package Basics_Command;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.io.FileUtils;
public class CopyFiles {
static Set<String> fileList = new HashSet<String>();
public static void getCurrentFile(){
File folderUAT = new File("D:\\UAT");
File[] listOfFilesUAT = folderUAT.listFiles();
for (int i = 0; i < listOfFilesUAT.length; i++) {
fileList.add(listOfFilesUAT[i].getName());
}
}
public static void main(String[] args) throws IOException {
getCurrentFile();
copyFiles("D:\\prod");
}
private static void copyFiles(String filePath) throws IOException {
File folder = new File(filePath);
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length<0) {
System.exit(0);
}
else {
for (int i = 0; i < listOfFiles.length; i++) {
if(!fileList.contains(listOfFiles[i].getName()) && !listOfFiles[i].isDirectory()) {
File copied = new File("D:\\UAT\\"+listOfFiles[i].getName());
FileUtils.copyFile(listOfFiles[i].getAbsoluteFile(), copied);
System.out.println(copied.getAbsolutePath());
}else if(listOfFiles[i].isDirectory()){
/*Path sourceDir=Paths.get(listOfFiles[i].getAbsolutePath());
Path targetDirectory = Paths.get("D:\\UAT\\"+listOfFiles[i].getName());
Files.copy(sourceDir, targetDirectory);*/
File f = new File("D:\\UAT\\"+listOfFiles[i].getName());
FileUtils.copyDirectory(listOfFiles[i],f );
}
}
}
}
}
Ответ 7
Копировать файл из одного места в другое значит, нужно копировать весь контент в другое место. 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!!!!!!!!!!!!!!");
}