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

字数 57阅读 665

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

    }

推荐阅读更多精彩内容