栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用Java复制文件并替换现有目标

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Java复制文件并替换现有目标

作为@assylias答案的补充:

如果您使用Java 7,请

File
完全删除。您想要的是
Path

要获得

Path
与文件系统上的路径匹配的对象,请执行以下操作:

Paths.get("path/to/file"); // argument may also be absolute

快速习惯它。需要注意的是,如果你仍然使用需要的API

File
Path
有一个
.toFile()
方法。

请注意,如果不幸的是您使用返回

File
对象的API ,则始终可以执行以下操作:

theFileObject.toPath()

但在您的代码中,使用

Path
。系统地。不用再想了。

编辑 可以使用NIO使用1.6将文件复制到另一个文件。请注意,该

Closer
课程是由Guava主持的:

public final class Closer    implements Closeable{    private final List<Closeable> closeables = new ArrayList<Closeable>();    // @Nullable is a JSR 305 annotation    public <T extends Closeable> T add(@Nullable final T closeable)    {        closeables.add(closeable);        return closeable;    }    public void closeQuietly()    {        try { close();        } catch (IOException ignored) {        }    }    @Override    public void close()        throws IOException    {        IOException toThrow = null;        final List<Closeable> l = new ArrayList<Closeable>(closeables);        Collections.reverse(l);        for (final Closeable closeable: l) { if (closeable == null)     continue; try {     closeable.close(); } catch (IOException e) {     if (toThrow == null)         toThrow = e; }        }        if (toThrow != null) throw toThrow;    }}// Copy one file to another using NIOpublic static void doCopy(final File source, final File destination)    throws IOException{    final Closer closer = new Closer();    final RandomAccessFile src, dst;    final FileChannel in, out;    try {        src = closer.add(new RandomAccessFile(source.getCanonicalFile(), "r");        dst = closer.add(new RandomAccessFile(destination.getCanonicalFile(), "rw");        in = closer.add(src.getChannel());        out = closer.add(dst.getChannel());        in.transferTo(0L, in.size(), out);        out.force(false);    } finally {        closer.close();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452731.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号