【问题标题】:Copy Directory/Folder Program Error (Java)复制目录/文件夹程序错误 (Java)
【发布时间】:2015-03-23 09:36:50
【问题描述】:

我想知道是否有人可以帮助我完成我的程序,因为我不知道我在哪里写错了。我的程序步骤如下:

  1. 向用户询问源目录和目标。源是要复制的目录;目标是新副本的父目录。

  2. 首先,您的程序应该在新位置创建一个与源目录同名的新目录。 (如果要复制整个磁盘,您可能需要对根目录做一些特殊的事情。根目录没有父目录,而且通常没有名称。)

  3. 那么你的程序应该为源目录内容中的每个项目创建一个包含 File 类对象的数组

  4. 接下来,它应该迭代数组,并为数组中的每一项 1.如果是文件,使用copyFile()方法将文件复制到新目录

    1. 如果是目录,递归调用该方法复制目录及其所有内容。

我的代码如下,我不明白我在这个程序上做错了什么,但不管输出结果是“文件不存在”。

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


public class DirectCopy {

    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.mkdirs();

    //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

【问题讨论】:

  • 你能放一个你在 dirName 和 destName 中放什么的例子吗?我不明白您为什么要尝试迭代刚刚创建的文件夹。而且我不明白您为什么尝试使用 dest+source 创建文件夹,如果两者都是绝对路径,它将无法工作。
  • 是的,很抱歉。 (dest + source) 发生的事情是我的教授为要求写了一个错误。我知道这很奇怪,但此刻我正在按照他说的去做。

标签: java file netbeans mkdir


【解决方案1】:

假设sourcedest 类似于C:\D:\New Dest,那么问题可能就在这行:File dirFile = new File (dest + source);

根据JavaDoc,该构造函数将类似于一个文件,它是两个字符串的连接。在上面的示例中,这将产生类似D:\New Dest\C: 的内容。

下面的代码没有失败:

    File a = new File("C:" + "D:\\New Dest");
    a.mkdirs();
    System.out.println(a.getAbsolutePath());

但是,似乎没有创建目录。我认为你需要做的是将这个:File dirFile = new File (dest + source); 重命名为:

File dirFile = new File (dest, new File(source).getName());

它应该创建您所追求的目录结构。请注意,对于根目录,getName() 将为空。

编辑:根据您的评论和@vincent 提到的,您正在创建一个新目录,将其命名为dirFile,您将在其中放置source 指定的相同目录结构的副本。 问题是这样的:entries = dirFile.listFiles();。您是说您的目录结构的来源是您创建的新文件,它应该是空的,因此,entries 应该是一个空数组。

由于数组为空,for 循环将立即退出(它根本不会执行)。您需要将这一行:entries = dirFile.listFiles(); 替换为:entries = new File(source).listFiles();

【讨论】:

  • 非常感谢!现在程序将文件夹复制到新的目的地,但由于某种原因,它不会将该目录中的内容带到新的目的地。你也可以帮我解决这个问题吗?
  • 嘿,我想知道是否有任何可能的方式可以向您发送消息,因为我注意到该程序出于某种原因没有调用 copyFile 方法。
  • @Ricardo3:我已经修改了我的答案来解决你的问题。如果您还有任何问题,请告诉我。
猜你喜欢
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
相关资源
最近更新 更多