复制目录及其所有内容 - Java - Netbeans

时间:2014-03-16 21:14:06

标签: java file netbeans recursion copy

我的目标是在Netbeans中编写一个Java程序来复制目录及其所有内容,包括子目录及其内容。为此,我首先要求用户输入要复制的源目录和目标。从这里开始,我的程序应该在新位置创建一个与源目录同名的新目录。然后我的程序应该为源目录的内容中的每个项创建一个包含File类对象的数组。接下来,我尝试迭代数组,并为每个项目 - 如果它是一个文件,它应该复制到新目录 - 如果它是一个目录,它应该递归调用此方法来复制目录及其所有内容

如果我能让它正常工作,这是一个非常有用的程序。我现在很难理解使该程序高效运行所需的全部逻辑。

当我运行该程序时,它返回无法找到该文件,但事实并非如此。所以我的代码必须在某处出错。任何帮助都会非常感谢大家。

谢谢。

 package copydirectories;

 /**
 * CSCI 112, Ch. 18 Ex. 5
 * @author zhughes3
 * Last edited Tuesday, March 11th, 2014 @ 9pm
 */

 import java.io.*;
 import java.util.Scanner;

 public class CopyDirectories {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws Exception {
    //Create a new instance of scanner to get user input
    Scanner scanner = new Scanner (System.in);

    //Ask user to input the directory to be copied
    System.out.print("Input directory to be copied.");

    //Save input as String
    String dirName = scanner.nextLine();

    //Ask user to input destination where direction will be copied
    System.out.print("Input destination directory will be moved to.");

    //Save input as String
    String destName = scanner.nextLine();

    //Run method to determine if it is a directory or file
    isDirFile(dirName, destName);


}//end main

public static void isDirFile (String source, String dest) throws Exception{
    //Create a File object for new directory in new location with same name
    //as source directory
    File dirFile = new File (dest + source);

    //Make the new directory
    dirFile.mkdir();

    //Create an array of File class objects for each item in the source
    //directory
    File[] entries; 

    //If source directory exists
    if (dirFile.exists()){
        //If the source directory is a directory
        if (dirFile.isDirectory()){

            //Get the data and load the array
            entries = dirFile.listFiles();

            //Iterate the array using alternate for statement
            for (File entry : entries){
                if (entry.isFile()){
                    copyFile (entry.getAbsolutePath(), dest);
                } //end if
                else {
                    isDirFile (entry.getAbsolutePath(), dest);
                }  //end else if
            }//end for
        }//end if
    }//end if
    else {
        System.out.println("File does not exist.");
    } //end else
}

public static void copyFile (String source, String dest) throws Exception {

    //declare Files
    File sourceFile = null;
    File destFile = null;

    //declare stream variables
    FileInputStream sourceStream = null;
    FileOutputStream destStream = null;

    //declare buffering variables
    BufferedInputStream bufferedSource = null;
    BufferedOutputStream bufferedDest = null;

    try {
        //Create File objects for source and destination files
        sourceFile = new File (source);
        destFile = new File (dest);

        //Create file streams for the source and destination
        sourceStream = new FileInputStream(sourceFile);
        destStream = new FileOutputStream(destFile);

        //Buffer the file streams with a buffer size of 8k
        bufferedSource = new BufferedInputStream(sourceStream,8182);
        bufferedDest = new BufferedOutputStream(destStream,8182);

        //Use an integer to transfer data between files
        int transfer;

        //Alert user as to what is happening
        System.out.println("Beginning file copy:");
        System.out.println("\tCopying " + source);
        System.out.println("\tTo      " + dest);

        //Read a byte while checking for End of File (EOF)
        while ((transfer = bufferedSource.read()) !=-1){

        //Write a byte
        bufferedDest.write(transfer);
    }//end while

    }//end try

    catch (IOException e){
        e.printStackTrace();
        System.out.println("An unexpected I/O error occurred.");
    }//end catch

    finally {
        //close file streams
        if (bufferedSource !=null)
            bufferedSource.close();

        if (bufferedDest !=null)
            bufferedDest.close();

        System.out.println("Your files have been copied correctly and "
                + "closed.");
    }//end finally
}//end copyDir

}//end class

1 个答案:

答案 0 :(得分:0)

如果您阅读JavaDocs,您会看到mkdir ...

  

创建此抽象路径名命名的目录。

这有点模糊,但基本上,它只会创建目录的最后一级。例如,如果您的路径为C:\this\is\a\long\path,则mkdir只会尝试在path末尾创建C:\this\is\a\long目录,但如果C:\this\is\a\long不存在,会失败。

相反,如果你使用mkdirs

  

创建此抽象路径名所指定的目录,包括any   必要但不存在的父目录。请注意,如果这样   操作失败它可能已经成功创建了一些   必要的父目录。

我还会检查这些方法的结果,因为它们会指示操作是否成功

我认为entries = dirFile.listFiles();看起来不对,你应该列出源目录中的文件,而不是目的地......