한 위치에서 다른 위치로 파일을 복사하는 방법은 무엇입니까?
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);
}
}
}
이것은 파일을 복사하지 않습니다.이 작업을 수행하는 가장 좋은 방법은 무엇입니까?
당신이 사용할 수있는 이 (또는 변형) :
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
또한 여러 OS에서 호환되도록하는 대신 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);
}
스트림 사용
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 파일 클래스 사용 :
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
Java> = 7에서 새 Java 파일 클래스를 사용하십시오.
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:
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.
Credits - @Scott: Standard concise way to copy a file in Java?
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() );
}
}
Files.exists()
Files.createDirectory()
Files.copy()
Overwriting Existing Files: Files.move()
Files.delete()
Files.walkFileTree() enter link description here
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.
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!!!!!!!!!!!!!!");
}
ReferenceURL : https://stackoverflow.com/questions/16433915/how-to-copy-file-from-one-location-to-another-location
'program tip' 카테고리의 다른 글
멤버 변수를 선언 된 순서대로 초기화해야하는 이유는 무엇입니까? (0) | 2020.12.28 |
---|---|
Java : 동기화 된 블록에서 wait () 잠금 해제 (0) | 2020.12.28 |
Java String 변수의 마지막 문자 제거 (0) | 2020.12.28 |
C #의 수학 최적화 (0) | 2020.12.28 |
상대 경로에서 절대 URL 가져 오기 (리팩터링 된 방법) (0) | 2020.12.28 |