your programing

Java에서 파일을 한 위치에서 다른 위치로 어떻게 이동합니까?

lovepro 2020. 10. 11. 11:07
반응형

Java에서 파일을 한 위치에서 다른 위치로 어떻게 이동합니까?


한 위치에서 다른 위치로 파일을 어떻게 이동합니까? 프로그램을 실행하면 해당 위치에서 생성 된 모든 파일이 자동으로 지정된 위치로 이동합니다. 어떤 파일이 이동되었는지 어떻게 알 수 있습니까?

미리 감사드립니다!


myFile.renameTo(new File("/the/new/place/newName.file"));

File # renameTo 는이를 수행합니다 (이름을 바꿀 수있을뿐만 아니라 최소한 동일한 파일 시스템에서 디렉토리간에 이동할 수도 있습니다).

이 추상 경로 이름으로 표시된 파일의 이름을 바꿉니다.

이 방법의 동작의 많은 측면은 본질적으로 플랫폼에 따라 다릅니다. 이름 바꾸기 작업은 한 파일 시스템에서 다른 파일 시스템으로 파일을 이동할 수없고 원 자성이 아닐 수 있으며 대상 추상 경로 이름을 가진 파일이있는 경우 성공하지 못할 수 있습니다. 이미 존재 함. 반환 값은 항상 이름 바꾸기 작업이 성공했는지 확인해야합니다.

보다 포괄적 인 솔루션이 필요한 경우 (예 : 디스크간에 파일을 이동하려는 경우) Apache Commons FileUtils # moveFile을 참조하십시오.


Java 7 이상에서는 Files.move(from, to, CopyOption... options).

Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);

자세한 내용은 파일 문서를 참조하십시오.


파일을 이동하려면 Jakarta Commons IOs FileUtils.moveFile을 사용할 수도 있습니다.

오류가 발생하면을 던지 IOException므로 예외가 발생하지 않으면 파일이 이동되었음을 알 수 있습니다.


File.renameToJava IO에서 Java에서 파일을 이동하는 데 사용할 수 있습니다. 또한 이 SO 질문을 참조하십시오 .


소스 및 대상 폴더 경로를 추가하기 만하면됩니다.

소스 폴더에서 대상 폴더로 모든 파일과 폴더를 이동합니다.

    File destinationFolder = new File("");
    File sourceFolder = new File("");

    if (!destinationFolder.exists())
    {
        destinationFolder.mkdirs();
    }

    // Check weather source exists and it is folder.
    if (sourceFolder.exists() && sourceFolder.isDirectory())
    {
        // Get list of the files and iterate over them
        File[] listOfFiles = sourceFolder.listFiles();

        if (listOfFiles != null)
        {
            for (File child : listOfFiles )
            {
                // Move files to destination folder
                child.renameTo(new File(destinationFolder + "\\" + child.getName()));
            }

            // Add if you want to delete the source folder 
            sourceFolder.delete();
        }
    }
    else
    {
        System.out.println(sourceFolder + "  Folder does not exists");
    }

자바 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

    return fileToMove.renameTo(new File(targetPath));
}

Java 7 (NIO 사용)

public boolean moveFile(String sourcePath, String targetPath) {

    boolean fileMoved = true;

    try {

        Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);

    } catch (Exception e) {

        fileMoved = false;
        e.printStackTrace();
    }

    return fileMoved;
}

You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:

  1. read the source file into memory
  2. write the content to a file at the new location
  3. delete the source file

File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.


Try this :-

  boolean success = file.renameTo(new File(Destdir, file.getName()));

Files.move(source, target, REPLACE_EXISTING);

You can use the Files object

Read more about Files


Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.

// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
    File tDir = new File(targetPath);
    if (tDir.exists()) {
        String newFilePath = targetPath+File.separator+sourceFile.getName();
        File movedFile = new File(newFilePath);
        if (movedFile.exists())
            movedFile.delete();
        return sourceFile.renameTo(new File(newFilePath));
    } else {
        LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
        return false;
    }       
}

참고URL : https://stackoverflow.com/questions/4645242/how-do-i-move-a-file-from-one-location-to-another-in-java

반응형