简体   繁体   中英

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.

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")

I would get IOException error

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. 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()方法似乎并未使用此文件夹,只是将文件保存在当前目录中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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