如何使用子目录,文件和zip文件复制目录

时间:2015-05-22 08:21:21

标签: java file nullpointerexception inputstream fileinputstream

我正在尝试复制目录(例如:我的文档,本地磁盘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);
        }
    }

此代码因生成错误而失败。错误只是发生,因为它'#34;转移"路径。我插入复制的路径是"我的文档"并以某种方式它试图复制"我的音乐"同样,最终在nullPointerException因为"我的音乐"超出了我的文件"。同样重要的是要注意,这只发生在某些输入位置,而不是所有时间。

我得到的错误如下。

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)

第52行

for (String file : files)

请帮我修复错误。

3 个答案:

答案 0 :(得分:2)

你可以使用这些方法:

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

只需走过文件树,然后在FileVisitor中复制。

示例如何使用工作代码:

将第一个示例更改为一行以下,将<Path>类型添加到FileVisitor,如下所示:

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

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

并且:http://www.studytrails.com/java-io/file-listing-directory-walking.jsp

答案 1 :(得分:0)

Apache Commons IO可以帮到你。看看FileUtils

实施例

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

如果您需要使用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);
        }
    }
}

答案 2 :(得分:0)

(抱歉自我广告......)

如果你使用Java 7,你可以试试one of my projects;这可以让你做你想做的事:

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

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

但请注意,它将在目的地中创建源;这可能不是你想要的。但是如果你只想复制内容,你可以这样做:

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);
    }
}

为什么我不在第二个例子中直接使用流:这是因为在lambdas中处理已检查异常的混乱;但是又一次,对于自我广告再次抱歉,在这种情况下你可能想要查看throwing-lambdas,在这种情况下复制目录条目可以这样做:

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);
}