我一直在尝试多种方法从 URL 下载文件并将其放入文件夹中。
public static void saveFile(String fileName,String fileUrl) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
boolean success = (new File("File")).mkdirs();
if (!success) {
Status.setText("Failed");
}
try {
saveFile("DownloadedFileName", "ADirectDownloadLinkForAFile");
} catch (MalformedURLException ex) {
Status.setText("MalformedURLException");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Status.setText("IOException Error");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
}
我在网上找到了这段代码,我是否正确使用它?
如果我这样做: saveFile("文件夹名称", "ADirectDownloadLinkForAFile")
我会收到IOException
错误
我希望我的代码做的是:
- 创建文件夹
- 下载文件
- 下载的文件转到刚刚创建的文件夹
抱歉,我是这里的新手。请帮忙
最佳答案
java中有多种从互联网下载文件的方法。 最简单的一种是使用缓冲区和流:
File theDir = new File("new folder");
// if the directory does not exist, create it
if (!theDir.exists())
{
System.out.println("creating directory: " + directoryName);
boolean result = theDir.mkdir();
if(result){
System.out.println("DIR created");
}
}
FileOutputStream out = new FileOutputStream(new File(theDir.getAbsolutePath() +"filename"));
BufferedInputStream in = new BufferedInputStream(new URL("URLtoYourFIle").openStream());
byte data[] = new byte[1024];
int count;
while((count = in.read(data,0,1024)) != -1)
{
out.write(data, 0, count);
}
只是基本概念。不要忘记关闭流;)
关于java - 将文件(.zip、.jar、...)下载到文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688274/