Programing

Java에서 한 디렉토리에서 다른 디렉토리로 파일 복사

lottogame 2020. 6. 18. 07:53
반응형

Java에서 한 디렉토리에서 다른 디렉토리로 파일 복사


Java를 사용하여 한 디렉토리에서 다른 디렉토리 (하위 디렉토리)로 파일을 복사하고 싶습니다. 텍스트 파일이있는 디렉토리 dir이 있습니다. dir의 처음 20 개 파일을 반복하고 dir 디렉토리의 다른 디렉토리로 복사하려고합니다.이 디렉토리는 반복 직전에 생성되었습니다. 코드에서 review(i 번째 텍스트 파일 또는 리뷰를 나타내는) 을에 복사하려고 합니다 trainingDir. 어떻게해야합니까? 그런 기능이없는 것 같습니다 (또는 찾을 수 없습니다). 감사합니다.

boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
    File review = reviews[i];

}

지금은 문제를 해결해야합니다

File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
    FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
    e.printStackTrace();
}

FileUtils버전 1.2부터 사용 가능한 Apache Commons-IO 라이브러리의 클래스 .

우리가 직접 모든 유틸리티를 작성하는 대신 타사 도구를 사용하는 것이 더 좋습니다. 시간과 기타 귀중한 자원을 절약 할 수 있습니다.


표준 API에는 아직 파일 복사 방법이 없습니다. 옵션은 다음과 같습니다.

  • FileInputStream, FileOutputStream 및 버퍼를 사용하여 바이트를 한 바이트에서 다른 바이트로 복사하거나 더 나은 방법으로 FileChannel.transferTo ()를 사용하여 직접 작성하십시오.
  • 사용자 Apache Commons의 FileUtils
  • Java 7에서 NIO2 대기

자바 7에서이 입니다 자바 파일을 복사 할 수있는 표준 방법 :

Files.copy.

고성능을 위해 O / S 기본 I / O와 통합됩니다.

Java로 파일을 복사하는 표준 간결한 방법 에 대한 A를 참조하십시오 . 사용법에 대한 자세한 설명.


Java 팁의 아래 예 는 다소 간단합니다. 그 후 파일 시스템을 다루는 작업을 훨씬 더 우아하고 우아하게 Groovy로 전환했습니다. 그러나 여기에 내가 과거에 사용한 Java 팁이 있습니다. 이를 방지하기 위해 필요한 강력한 예외 처리 기능이 없습니다.

 public void copyDirectory(File sourceLocation , File targetLocation)
    throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]),
                        new File(targetLocation, children[i]));
            }
        } else {

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetLocation);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
    }

파일을 복사하고 이동하지 않으려면 다음과 같이 코딩하면됩니다.

private static void copyFile(File sourceFile, File destFile)
        throws IOException {
    if (!sourceFile.exists()) {
        return;
    }
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        destination.transferFrom(source, 0, source.size());
    }
    if (source != null) {
        source.close();
    }
    if (destination != null) {
        destination.close();
    }

}

아파치 커먼즈 Fileutils 가 편리합니다. 아래 활동을 할 수 있습니다.

  1. 한 디렉토리에서 다른 디렉토리로 파일 복사

    사용하다 copyFileToDirectory(File srcFile, File destDir)

  2. 한 디렉토리에서 다른 디렉토리로 디렉토리 복사

    사용하다 copyDirectory(File srcDir, File destDir)

  3. 한 파일의 내용을 다른 파일로 복사

    사용하다 static void copyFile(File srcFile, File destFile)


Spring Framework 에는 Apache Commons Lang과 같은 많은 유사한 util 클래스가 있습니다. 그래서org.springframework.util.FileSystemUtils

File src = new File("/home/user/src");
File dest = new File("/home/user/dest");
FileSystemUtils.copyRecursively(src, dest);

File sourceFile = new File("C:\\Users\\Demo\\Downloads\\employee\\"+img);
File destinationFile = new File("\\images\\" + sourceFile.getName());

FileInputStream fileInputStream = new FileInputStream(sourceFile);
FileOutputStream fileOutputStream = new FileOutputStream(
                destinationFile);

int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
    fileOutputStream.write(bufffer, 0, bufferSize);
}
fileInputStream.close();
fileOutputStream.close();

간단한 해결책을 찾고있는 것 같습니다 (좋은 것). Apache Common의 FileUtils.copyDirectory를 사용하는 것이 좋습니다 .

파일 날짜를 유지하면서 전체 디렉토리를 새 위치에 복사합니다.

이 메소드는 지정된 디렉토리와 모든 하위 디렉토리 및 파일을 지정된 대상으로 복사합니다. 대상은 디렉토리의 새 위치 및 이름입니다.

대상 디렉토리가 없으면 작성됩니다. 대상 디렉토리가 존재하면이 방법은 소스를 대상과 병합하고 소스가 우선합니다.

코드는 다음과 같이 멋지고 단순 할 수 있습니다.

File trgDir = new File("/tmp/myTarget/");
File srcDir = new File("/tmp/mySource/");

FileUtils.copyDirectory(srcDir, trgDir);

import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);

출처 : https://docs.oracle.com/javase/tutorial/essential/io/copy.html


Apache commons FileUtils는 전체 디렉토리를 복사하지 않고 소스에서 대상 디렉토리 로 파일이동 하려는 경우에 유용합니다 .

for (File srcFile: srcDir.listFiles()) {
    if (srcFile.isDirectory()) {
        FileUtils.copyDirectoryToDirectory(srcFile, dstDir);
    } else {
        FileUtils.copyFileToDirectory(srcFile, dstDir);
    }
}

디렉토리를 건너 뛰려면 다음을 수행하십시오.

for (File srcFile: srcDir.listFiles()) {
    if (!srcFile.isDirectory()) {
        FileUtils.copyFileToDirectory(srcFile, dstDir);
    }
}

이 스레드 에서 Mohit의 답변에서 영감을 얻었습니다 . Java 8에만 해당됩니다.

다음을 사용하여 한 폴더에서 다른 폴더로 모든 항목을 반복적으로 복사 할 수 있습니다.

public static void main(String[] args) throws IOException {
    Path source = Paths.get("/path/to/source/dir");
    Path destination = Paths.get("/path/to/dest/dir");

    List<Path> sources = Files.walk(source).collect(toList());
    List<Path> destinations = sources.stream()
            .map(source::relativize)
            .map(destination::resolve)
            .collect(toList());

    for (int i = 0; i < sources.size(); i++) {
        Files.copy(sources.get(i), destinations.get(i));
    }
}

스트림 스타일 FTW.

2019-06-10 업데이트 : 중요한 참고 사항-Files.walk 호출로 얻은 스트림을 닫습니다 (예 : 리소스를 사용하여 try-with 리소스 사용). 요점은 @jannis에게 감사합니다.


다음은 파일을 소스 위치에서 대상 위치로 복사하는 Brian의 수정 된 코드입니다.

public class CopyFiles {
 public static void copyFiles(File sourceLocation , File targetLocation)
    throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }
            File[] files = sourceLocation.listFiles();
            for(File file:files){
                InputStream in = new FileInputStream(file);
                OutputStream out = new FileOutputStream(targetLocation+"/"+file.getName());

                // Copy the bits from input stream to output stream
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            }            
        }
    }

자바 8

Path sourcepath = Paths.get("C:\\data\\temp\\mydir");
        Path destinationepath = Paths.get("C:\\data\\temp\\destinationDir");        
        Files.walk(sourcepath)
             .forEach(source -> copy(source, destinationepath.resolve(sourcepath.relativize(source)))); 

복사 방법

static void copy(Path source, Path dest) {
        try {
            Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

소스 파일을 새 파일로 복사하고 원본을 삭제하면이 문제를 해결할 수 있습니다.

public class MoveFileExample {

 public static void main(String[] args) {   

    InputStream inStream = null;
    OutputStream outStream = null;

    try {

        File afile = new File("C:\\folderA\\Afile.txt");
        File bfile = new File("C:\\folderB\\Afile.txt");

        inStream = new FileInputStream(afile);
        outStream = new FileOutputStream(bfile);

        byte[] buffer = new byte[1024];

        int length;
        //copy the file content in bytes 
        while ((length = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, length);
        }

        inStream.close();
        outStream.close();

        //delete the original file
        afile.delete();

        System.out.println("File is copied successful!");

    } catch(IOException e) {
        e.printStackTrace();
    }
 }
}

사용하다

org.apache.commons.io.FileUtils

너무 편리합니다


File dir = new File("D:\\mital\\filestore");
File[] files = dir.listFiles(new File_Filter("*"+ strLine + "*.txt"));
for (File file : files){    
    System.out.println(file.getName());

    try {
        String sourceFile=dir+"\\"+file.getName();
        String destinationFile="D:\\mital\\storefile\\"+file.getName();
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        FileOutputStream fileOutputStream = new FileOutputStream(
                        destinationFile);
        int bufferSize;
        byte[] bufffer = new byte[512];
        while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
            fileOutputStream.write(bufffer, 0, bufferSize);
        }
        fileInputStream.close();
        fileOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

NIO 클래스는 이것을 매우 간단하게 만듭니다.

http://www.javalobby.org/java/forums/t17036.html


다음 코드를 사용하여 업로드 CommonMultipartFile된 폴더 로 전송하고 해당 파일을 webapps (예 : 웹 프로젝트 폴더)의 대상 폴더로 복사하십시오.

    String resourcepath = "C:/resources/images/" + commonsMultipartFile.getOriginalFilename();

    File file = new File(resourcepath);
    commonsMultipartFile.transferTo(file);

    //Copy File to a Destination folder
    File destinationDir = new File("C:/Tomcat/webapps/myProject/resources/images/");
    FileUtils.copyFileToDirectory(file, destinationDir);

한 디렉토리에서 다른 디렉토리로 파일 복사 ...

FileChannel source=new FileInputStream(new File("source file path")).getChannel();
FileChannel desti=new FileOutputStream(new File("destination file path")).getChannel();
desti.transferFrom(source, 0, source.size());
source.close();
desti.close();

여기에 단순히 하나의 폴더에서 다른 폴더로 데이터를 복사하는 Java 코드가 있습니다. 소스 및 대상의 입력을 제공하면됩니다.

import java.io.*;

public class CopyData {
static String source;
static String des;

static void dr(File fl,boolean first) throws IOException
{
    if(fl.isDirectory())
    {
        createDir(fl.getPath(),first);
        File flist[]=fl.listFiles();
        for(int i=0;i<flist.length;i++)
        {

            if(flist[i].isDirectory())
            {
                dr(flist[i],false);
            }

            else
            {

                copyData(flist[i].getPath());
            }
        }
    }

    else
    {
        copyData(fl.getPath());
    }
}

private static void copyData(String name) throws IOException {

        int i;
        String str=des;
        for(i=source.length();i<name.length();i++)
        {
            str=str+name.charAt(i);
        }
        System.out.println(str);
        FileInputStream fis=new FileInputStream(name);
        FileOutputStream fos=new FileOutputStream(str);
        byte[] buffer = new byte[1024];
        int noOfBytes = 0;
         while ((noOfBytes = fis.read(buffer)) != -1) {
             fos.write(buffer, 0, noOfBytes);
         }


}

private static void createDir(String name, boolean first) {

    int i;

    if(first==true)
    {
        for(i=name.length()-1;i>0;i--)
        {
            if(name.charAt(i)==92)
            {
                break;
            }
        }

        for(;i<name.length();i++)
        {
            des=des+name.charAt(i);
        }
    }
    else
    {
        String str=des;
        for(i=source.length();i<name.length();i++)
        {
            str=str+name.charAt(i);
        }
        (new File(str)).mkdirs();
    }

}

public static void main(String args[]) throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("program to copy data from source to destination \n");
    System.out.print("enter source path : ");
    source=br.readLine();
    System.out.print("enter destination path : ");
    des=br.readLine();
    long startTime = System.currentTimeMillis();
    dr(new File(source),true);
    long endTime   = System.currentTimeMillis();
    long time=endTime-startTime;
    System.out.println("\n\n Time taken = "+time+" mili sec");
}

}

이것은 당신이 원하는 것에 대한 작동 코드입니다.


다음 코드를 사용하여 한 디렉토리에서 다른 디렉토리로 파일을 복사 할 수 있습니다

// parent folders of dest must exist before calling this function
public static void copyTo( File src, File dest ) throws IOException {
     // recursively copy all the files of src folder if src is a directory
     if( src.isDirectory() ) {
         // creating parent folders where source files is to be copied
         dest.mkdirs();
         for( File sourceChild : src.listFiles() ) {
             File destChild = new File( dest, sourceChild.getName() );
             copyTo( sourceChild, destChild );
         }
     } 
     // copy the source file
     else {
         InputStream in = new FileInputStream( src );
         OutputStream out = new FileOutputStream( dest );
         writeThrough( in, out );
         in.close();
         out.close();
     }
 }

    File file = fileChooser.getSelectedFile();
    String selected = fc.getSelectedFile().getAbsolutePath();
     File srcDir = new File(selected);
     FileInputStream fii;
     FileOutputStream fio;
    try {
         fii = new FileInputStream(srcDir);
         fio = new FileOutputStream("C:\\LOvE.txt");
         byte [] b=new byte[1024];
         int i=0;
        try {
            while ((fii.read(b)) > 0)
            {

              System.out.println(b);
              fio.write(b);
            }
            fii.close();
            fio.close();

한 디렉토리에서 다른 디렉토리로 파일을 복사하는 다음 코드

File destFile = new File(targetDir.getAbsolutePath() + File.separator
    + file.getName());
try {
  showMessage("Copying " + file.getName());
  in = new BufferedInputStream(new FileInputStream(file));
  out = new BufferedOutputStream(new FileOutputStream(destFile));
  int n;
  while ((n = in.read()) != -1) {
    out.write(n);
  }
  showMessage("Copied " + file.getName());
} catch (Exception e) {
  showMessage("Cannot copy file " + file.getAbsolutePath());
} finally {
  if (in != null)
    try {
      in.close();
    } catch (Exception e) {
    }
  if (out != null)
    try {
      out.close();
    } catch (Exception e) {
    }
}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFiles {
    private File targetFolder;
    private int noOfFiles;
    public void copyDirectory(File sourceLocation, String destLocation)
            throws IOException {
        targetFolder = new File(destLocation);
        if (sourceLocation.isDirectory()) {
            if (!targetFolder.exists()) {
                targetFolder.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i = 0; i < children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]),
                        destLocation);

            }
        } else {

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetFolder + "\\"+ sourceLocation.getName(), true);
            System.out.println("Destination Path ::"+targetFolder + "\\"+ sourceLocation.getName());            
            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            noOfFiles++;
        }
    }

    public static void main(String[] args) throws IOException {

        File srcFolder = new File("C:\\sourceLocation\\");
        String destFolder = new String("C:\\targetLocation\\");
        CopyFiles cf = new CopyFiles();
        cf.copyDirectory(srcFolder, destFolder);
        System.out.println("No Of Files got Retrieved from Source ::"+cf.noOfFiles);
        System.out.println("Successfully Retrieved");
    }
}

Java 7에서는 그렇게 복잡하지 않고 가져 오기가 필요하지 않습니다.

renameTo( )방법은 파일 이름을 변경합니다.

public boolean renameTo( File destination)

예를 들어, src.txt현재 작업 디렉토리 의 파일 이름을로 변경하려면 다음과 같이 dst.txt작성하십시오.

File src = new File(" src.txt"); File dst = new File(" dst.txt"); src.renameTo( dst); 

그게 다야.

참고:

Harold, Elliotte Rusty (2006-05-16). Java I / O (p. 393). 오라일리 미디어. 킨들 에디션.


다음 코드를 사용하여 한 디렉토리에서 다른 디렉토리로 파일을 복사 할 수 있습니다

public static void copyFile(File sourceFile, File destFile) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(sourceFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        } catch(Exception e){
            e.printStackTrace();
        }
        finally {
            in.close();
            out.close();
        }
    }

재귀 함수에 따라 누군가에게 도움이된다면 작성했습니다. sourcedirectory 내의 모든 파일을 destinationDirectory로 복사합니다.

예:

rfunction("D:/MyDirectory", "D:/MyDirectoryNew", "D:/MyDirectory");

public static void rfunction(String sourcePath, String destinationPath, String currentPath) {
    File file = new File(currentPath);
    FileInputStream fi = null;
    FileOutputStream fo = null;

    if (file.isDirectory()) {
        String[] fileFolderNamesArray = file.list();
        File folderDes = new File(destinationPath);
        if (!folderDes.exists()) {
            folderDes.mkdirs();
        }

        for (String fileFolderName : fileFolderNamesArray) {
            rfunction(sourcePath, destinationPath + "/" + fileFolderName, currentPath + "/" + fileFolderName);
        }
    } else {
        try {
            File destinationFile = new File(destinationPath);

            fi = new FileInputStream(file);
            fo = new FileOutputStream(destinationPath);
            byte[] buffer = new byte[1024];
            int ind = 0;
            while ((ind = fi.read(buffer))>0) {
                fo.write(buffer, 0, ind);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if (null != fi) {
                try {
                    fi.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != fo) {
                try {
                    fo.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

외부 라이브러리를 사용하지 않고 java.nio 클래스 대신 java.io를 사용하려는 경우이 간결한 메소드를 사용하여 폴더 및 모든 컨텐츠를 복사 할 수 있습니다.

/**
 * Copies a folder and all its content to another folder. Do not include file separator at the end path of the folder destination.
 * @param folderToCopy The folder and it's content that will be copied
 * @param folderDestination The folder destination
 */
public static void copyFolder(File folderToCopy, File folderDestination) {
    if(!folderDestination.isDirectory() || !folderToCopy.isDirectory())
        throw new IllegalArgumentException("The folderToCopy and folderDestination must be directories");

    folderDestination.mkdirs();

    for(File fileToCopy : folderToCopy.listFiles()) {
        File copiedFile = new File(folderDestination + File.separator + fileToCopy.getName());

        try (FileInputStream fis = new FileInputStream(fileToCopy);
             FileOutputStream fos = new FileOutputStream(copiedFile)) {

            int read;
            byte[] buffer = new byte[512];

            while ((read = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

내 지식에 따라 가장 좋은 방법은 다음과 같습니다.

    public static void main(String[] args) {

    String sourceFolder = "E:\\Source";
    String targetFolder = "E:\\Target";
    File sFile = new File(sourceFolder);
    File[] sourceFiles = sFile.listFiles();
    for (File fSource : sourceFiles) {
        File fTarget = new File(new File(targetFolder), fSource.getName());
        copyFileUsingStream(fSource, fTarget);
        deleteFiles(fSource);
    }
}

    private static void deleteFiles(File fSource) {
        if(fSource.exists()) {
            try {
                FileUtils.forceDelete(fSource);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void copyFileUsingStream(File source, File dest) {
        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);
            }
        } catch (Exception ex) {
            System.out.println("Unable to copy file:" + ex.getMessage());
        } finally {
            try {
                is.close();
                os.close();
            } catch (Exception ex) {
            }
        }
    }

참고 URL : https://stackoverflow.com/questions/1146153/copying-files-from-one-directory-to-another-in-java

반응형