首页 > 解决方案 > 如何将文件下载到java中的特定文件夹中?

问题描述

我正在开发一个应用程序,它将第 3 方依赖项下载到特定文件夹,然后对其执行依赖项检查。下载的文件可以是任何类型,可以是 zip、jar 或 ba 文件夹。我正在尝试找到一个代码示例,但似乎对我没有任何用处。我在java中尝试过NIO,但这似乎只适用于写入特定文件而不是文件夹。下面是我使用 NIO 的代码


        // Checking If The File Exists At The Specified Location Or Not
        Path filePathObj = Paths.get(filePath);
        boolean fileExists = Files.exists(filePathObj);
        if(fileExists) {
            try {
                urlObj = new URL(sampleUrl);
                rbcObj = Channels.newChannel(urlObj.openStream());
                fOutStream = new FileOutputStream(filePath);

                fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
                System.out.println("! File Successfully Downloaded From The Url !");
            } catch (IOException ioExObj) {
                System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
            } finally {
                try {
                    if(fOutStream != null){
                        fOutStream.close();
                    }
                    if(rbcObj != null) {
                        rbcObj.close();
                    }
                } catch (IOException ioExObj) {
                    System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
                }
            }
        } else {
            System.out.println("File Not Present! Please Check!");
        }```

标签: java

解决方案


使用 OKHttpClient 下载文件并放置在文件夹中。

        Request request = new Request.Builder().url(downloadUrl).build();
        Response response;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                fileName = abc.zip
                Path targetPath = new File(inDir + File.separator + fileName).toPath();
                try (FileOutputStream fos = new FileOutputStream(targetPath)) {
                    fos.write(response.body().bytes());
                }
                return 0;
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }```

推荐阅读