zoukankan      html  css  js  c++  java
  • Java复制、移动和删除文件

    复制文件:

    Files.copy(fromPath,toPath);

    例如:

    Files.copy(Paths.get("E:\A.txt"), Paths.get("F:\A.txt"));// 将E:\A.txt复制到F:\A.txt

    这是Java 的API(注意:没有copy(String,String);的方法的!):

    Modifier and Type Method Description
    static long copy(InputStream in, Path target, CopyOption... options) Copies all bytes from an input stream to a file.
    static long copy(Path source, OutputStream out) Copies all bytes from a file to an output stream.
    static Path copy(Path source, Path target, CopyOption... options) Copy a file to a target file.

    移动文件(复制并删除源文件):

    Files.move(fromPath,toPath);

    例如:

    Files.move(Paths.get("E:\A.txt"), Paths.get("F:\A.txt"));//将E:\A.txt移动到F:\A.txt

    如果目标路径已经存在,复制或移动将失败,抛出异常java.nio.file.FileAlreadyExistsException。

    覆盖已有的目标路径,使用StandardCopyOption.REPLACE_EXISTING;例如:

    Files.move(Paths.get("E:\A.txt"), Paths.get("F:\A.txt"), StandardCopyOption.REPLACE_EXISTING);

    复制所有的文件属性,使用StandardCopyOption.COPY_ATTRIBUTES。

    删除文件:

    Files.delete(path);

    例如:

    Files.delete(Paths.get("E:\A.txt"));//删除E:\A.txt

    如果删除文件不存在,会抛出异常java.nio.file.NoSuchFileException。因此,可以使用deleteIfExists(path)方法:

    boolean deleted = Files.deleteIfExists(path);
  • 相关阅读:
    ssh 无密码互通
    React之jsx转js
    分布式事务参考
    js跨域解决方案
    idea编译时JDK版本变化
    计数算法
    Rocketmq消息持久化
    rocketmq安装
    nginx高可用配置
    nginx负载均衡设置
  • 原文地址:https://www.cnblogs.com/niudaxianren/p/10018487.html
Copyright © 2011-2022 走看看