JavaNIO 下载网络文件保存本地报java.nio.file.AccessDeniedException:无权限操作

JavaNIO 下载文件保存本地报java.nio.file.AccessDeniedException:无权限操作

异常代码如下:

    /**
     * nio下载文件到本地并保存
     * @param url
     * @param filePath
     * @param fileName
     */
    public static void downloadByNIO(String url, String filePath, String fileName) {
        try (InputStream in = new URL(url).openStream()) {
            Path target = Paths.get(filePath, fileName);
            Files.createDirectories(target.getParent());
            Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

异常信息如下:
java.nio.file.AccessDeniedException:文件路径

解决方法:增加文件的读写权限

    /**
     * nio下载文件到本地并保存
     * @param url
     * @param filePath
     * @param fileName
     */
    public static void downloadByNIO(String url, String filePath, String fileName) {
        try (InputStream ins = new URL(url).openStream()) {
            Path target = Paths.get(filePath, fileName);
            //设置获取全部权限
            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx");
            FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
            Files.createDirectories(target.getParent(),fileAttributes);
            Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,894评论 0 9
  • 1、IO介绍 在前期的学习上述知识点的过程中,我们书写的任何程序,它运行的时候都会有数据的产生,比如时间数据,而这...
    Villain丶Cc阅读 1,569评论 0 3
  • Java 语言支持的类型分为两类:基本类型和引用类型。整型(byte 1, short 2, int 4, lon...
    xiaogmail阅读 1,443评论 0 10
  • 这一场毫无征兆的雪 轻轻的经过你的窗外 起初你是欣喜的 为这不期而遇的美妙 突然你泪流满面 这该死的雪惊醒了你的哀...
    遇见小A的小c阅读 286评论 0 6

友情链接更多精彩内容