java - 如何将文件下载到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!");
}```
解决方案
使用 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());
}```
推荐阅读
- javascript - 当浏览器处于全屏模式时,如何禁用所有链接?
- c# - SqlDataSource 中的日期时间转换
- autodesk-forge - 如何为 Autodesk forge 创建 3d 图钉扩展?
- c - Dev C++ 未能执行错误 193 %1 不是有效的 win32 应用程序 | C 编程
- reactjs - 如何使用钩子以 MultiStep 反应形式保存 MultiSelect 值
- python-3.x - 卷积神经网络中的过拟合问题及决定卷积层和dence层的参数
- powershell - 通过 Out-GridView 管道后获取原始对象
- python - Django - 有没有更好的方法来发送批量 Twilio 短信?
- python - Python Tkinter - 使用命令功能
- mysql - 在mysql中对字母数字和数字列进行排序