简体   繁体   English

如何复制目录及其子目录,文件和zip文件

[英]How to copy a directory with its sub directories , files and zip files

I am trying to copy directories (ex: My documents, Local Disk D) with all of its contents.The code I used is below. 我正在尝试复制包含所有内容的目录(例如:我的文档,本地磁盘D)。我使用的代码如下。

 public void copyFolder(File inputLocation, File outputLocation) throws IOException
    {
       // FileUtils.copyDirectory(inputLocation, outputLocation);

        if (inputLocation.isDirectory())
        {

            //if directory not exists, create it
            if (!outputLocation.exists())
            {
                outputLocation.mkdir();
                System.out.println("Directory copied from "
                        + inputLocation + "  to " + outputLocation);
            }



            //list all the directory contents
            String files[] = inputLocation.list();

            for (String file : files)
            {
                //construct the src and dest file structure
                File srcFile = new File(inputLocation, file);
                File destFile = new File(outputLocation, file);
                //recursive copy
                copyFolder(srcFile, destFile);
            }

        } else
        {
            //if file, then copy it
            //Use bytes stream to support all file types
            InputStream in = new FileInputStream(inputLocation);
            OutputStream out = new FileOutputStream(outputLocation);

            byte[] buffer = new byte[1024];

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

            in.close();
            out.close();
            System.out.println("File copied from " + inputLocation + " to " + outputLocation);
        }
    }

This code fails as it generates an error. 该代码失败,因为它会生成一个错误。 The error is simply happening because it "shifts" the path. 该错误只是在发生,因为它“改变”了路径。 The path I inserted to copy is "My Documents" and somehow it tried to copy "My Music" as well, which ended up in nullPointerException because the "My Music" is outside of "My Documents". 我插入的复制路径是“我的文档”,并且以某种方式尝试复制“我的音乐”,由于“我的音乐”不在“我的文档”之外,因此最终导致nullPointerException It is also important to note that this is happening only for some input locations, not all the time. 同样重要的是要注意,这种情况仅在某些输入位置发生,而不是一直发生。

The error I get is below. 我得到的错误如下。

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at xxx.xxx.xxx.xxxx.xxxxx1.copyFolder(FolderCopy.java:52)
    at xxx.xxx.xxx.xxxx.xxxxx1.FolderCopy.copyFolder(FolderCopy.java:58)
    at xxx.xxx.xxx.xxxx.xxxxx1.ExpressWizard.noCompresionCheckBoxActionPerformed(ExpressWizard.java:2481)
    at xxx.xxx.xxx.xxxx.xxxxx1.ExpressWizard.access$4900(ExpressWizard.java:38)
    at xxx.xxx.xxx.xxxx.xxxxx1.ExpressWizard$30.actionPerformed(ExpressWizard.java:1413)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.java:308)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:751)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:702)
    at java.awt.EventQueue$3.run(EventQueue.java:696)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:724)
    at java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:721)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:109)
    at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:184)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:229)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:227)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:227)
    at java.awt.Dialog.show(Dialog.java:1084)
    at java.awt.Component.show(Component.java:1654)
    at java.awt.Component.setVisible(Component.java:1606)
    at java.awt.Window.setVisible(Window.java:1014)
    at java.awt.Dialog.setVisible(Dialog.java:1005)
    at com.theace.backupsystem.view.HomePanel.clickPanel01MouseClicked(HomePanel.java:653)
    at xxx.xxx.xxx.xxxx.xxxxx1.HomePanel.access$000(HomePanel.java:16)
    at xxx.xxx.xxx.xxxx.xxxxx1.HomePanel$1.mouseClicked(HomePanel.java:120)
    at java.awt.Component.processMouseEvent(Component.java:6528)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4542)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:751)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:702)
    at java.awt.EventQueue$3.run(EventQueue.java:696)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:724)
    at java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:721)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

The line 52 is 第52行是

for (String file : files)

Please help me to fix my errors . 请帮助我纠正错误。

you could use these methods: 您可以使用以下方法:

    Files.copy(source, target, options)
    Files.walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor) throws IOException

Just walk thru the file tree, and in the FileVisitor do the copy. 只需遍历文件树,然后在FileVisitor中进行复制。

example how to do that with working code: 示例如何使用工作代码做到这一点:

change in this first example below one line, add the <Path> type to FileVisitor, like this: 在第一个示例的第一行下面进行更改,将<Path>类型添加到FileVisitor,如下所示:

        Files.walkFileTree(source, options, Integer.MAX_VALUE, new FileVisitor<Path>() {....

http://javatutorialhq.com/java/example-source-code/io/nio/folder-copy/ http://javatutorialhq.com/java/example-source-code/io/nio/folder-copy/

and this: http://www.studytrails.com/java-io/file-listing-directory-walking.jsp 和这个: http : //www.studytrails.com/java-io/file-listing-directory-walking.jsp

Apache Commons IO can do the trick for you. Apache Commons IO可以为您解决问题。 Have a look at FileUtils . 看看FileUtils

Example

File srcDir = new File("D:");
File destDir = new File("C:");
FileUtils.copyFolder(srcDir, destDir);

If you need to use java7 or + 如果您需要使用java7或+

public void copy(File source, File target) throws IOException {
    if (source.isDirectory())
        copyFolder(source, target);
    else
        copyFile(source, target);
}

private void copyFolder(File source, File target) throws IOException {
    if (!target.exists())
        target.mkdir();

    for (String f : source.list())
        copy(new File(source, f), new File(target, f));
}

private void copyFile(File source, File target) throws IOException {        
    try (
            InputStream in = new FileInputStream(source);
            OutputStream out = new FileOutputStream(target)
    ) {
        byte[] buf = new byte[1024];
        int length;
        while ((length = in.read(buf)) > 0) {
            out.write(buf, 0, length);
        }
    }
}

(sorry for the self ad...) (对不起,自我广告...)

If you use Java 7, you can have a go and try one of my projects ; 如果您使用Java 7,则可以尝试一下我的一个项目 this allows you to do what you want: 这使您可以做自己想做的事情:

final Path src = Paths.get(srcdir);
final Path dst = Paths.get(dstdir);

MoreFiles.copyRecursive(src, dst, RecursionMode.KEEP_GOING);

Note however that it will create the source in the destination; 但是请注意,它将在目标位置创建源。 this may not be what you want. 这可能不是您想要的。 But then if you only want to copy the contents you can do that: 但是,如果您只想复制内容,则可以执行以下操作:

if (Files.isRegularFile(src))
    Files.copy(src, dst.resolve(src.getFileName().toString());
else {
    try (
        final Stream<Path> files = Files.list(src);
    ) {
        final List<Path> list = files.collect(Collectors.toList());
        for (final Path entry: list)
            MoreFiles.copyRecursive(entry, dst, RecursionMode.KEEP_GOING);
    }
}

Why I don't use the stream directly in the second example: it's because of the mess of handling checked exceptions in lambdas; 为什么在第二个示例中我不直接使用流:这是因为在lambda中处理检查的异常一团糟; but then again, and sorry for the self ad again , you may want to have a look at throwing-lambdas in this case, in which case copying directory entries can be done this way: 但话又说回来,并再次为自己的广告对不起,你可能想看看投掷lambda表达式在这种情况下,在这种情况下复制目录条目可以做到这样:

final Consumer<Path> copy 
    = Throwing.consumer(entry -> MoreFiles.copyRecursive(entry, dst, RecursionMode.KEEP_GOING);

try (
    final Stream<Path> files = Files.list(src);
) {
    files.forEach(copy);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从目录和子目录复制具有某些扩展名的所有文件? - How to copy all files with certain extensions from a directory and sub directories? 将目录,子目录和文件复制到SD卡-Android - Copy directory ,sub directories and files to sd card - android 读取目录中的所有文件,包括其子目录 - Reading all files in a directory including its sub directories 如何列出目录及其所有子目录中的所有文件 - How to list all files within a directory and all its sub-directories java如何将不同的子目录和文件移动到一个目录 - how to move different sub directories and files in to one directory in java Eclipse在没有文件的Antlr生成的代码目录上显示警告,但在其子目录上不显示警告 - Eclipse shows warning on Antlr generated code directory with no files, but not on its sub-directories 通过目录及其子目录中的所有文件搜索存储在数组列表中的值 - searching for values stored in an arraylist through all the files within a directory and its sub directories 在目录中搜索文件及其在Java中的子目录 - Search files in directory and its sub directory in java 读取多个文件 zip 文件有多个子目录 - Read multiple files zip file with multiple sub directories 如何检查文件是否是目录,递归地对其子目录及其内容执行相同操作并将它们复制到另一个位置 - How do I check whether a file is a directory, do the same for its sub directories and their contents recursively and copy them to another location
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM