简体   繁体   English

将文件(.zip,.jar等)下载到文件夹

[英]Downloading files(.zip, .jar,…) to a folder

I have been trying many ways of downloading a file from a URL and putting it in a folder. 我一直在尝试从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);
    }

I found this code on the net, am i using it correctly? 我在网上找到了此代码,我使用正确吗?

If i did: saveFile("FolderName", "ADirectDownloadLinkForAFile") 如果我这样做:saveFile(“ FolderName”,“ ADirectDownloadLinkForAFile”)

I would get IOException error 我会得到IOException错误

What I want my code to do is: 我想要我的代码做的是:

  1. Create folder 创建文件夹
  2. Download file 下载文件
  3. Downloaded file to go to the just created folder 下载的文件转到刚创建的文件夹

I'm a newbie here sorry. 我是新手,对不起。 Please help 请帮忙

There are various ways in java to download a file from the internet. Java中有多种方法可以从Internet下载文件。 The easiest one is to use a buffer and a stream: 最简单的方法是使用缓冲区和流:

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

Just the basic concept. 只是基本概念。 Dont forget the close the streams ;) 不要忘记关闭小溪;)

File.mkdirs()语句似乎正在创建一个名为Files的文件夹,但saveFile()方法似乎并未使用此文件夹,只是将文件保存在当前目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM