Java操作文件 复制、移动和删除

阿超 发表于 2009-08-15 14:20 | 来源:Java豆 | 阅读 167 次

1、删除
          在Java中,删除文件非常简单,仅仅是一个方法调用
        

new File("file path").delete();

2、移动
移动文件和删除文件同样简单,也只需要一个方法调用:

new File("source file path").renameTo(new File("destination file path"));

3、复制
Java中复制文件需要比较复杂的操作,因为没有API来完成该任务。下面是一个将文件从一个目录复制到另一个目录的例子:

public void copyFiles(String source, String destination) throws IOException {
    File srcDir = new File(source);
    File[] files = srcDir.listFiles();    

    FileChannel in = null;
    FileChannel out = null;
    for (File file : files) {
        try {
            in = new FileInputStream(file).getChannel();
            File outFile = new File(destination, file.getName());
            out = new FileOutputStream(outFile).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }
}

上面的代码中使用Java5中的NIO API,它能快速的完成任务

关键字: , ,
喜欢Java豆技术站点的文章,那就通过 RSS Feed 功能订阅阅读吧!

我要评论

*

* 绝不会泄露



返回首页 | 关于我们 | 联系我们 | 广告合作 | 网站地图 | 友情链接 | 版权声明 | 模板设计