Java如何利用url下载MP3保存到本地?

Python023

Java如何利用url下载MP3保存到本地?,第1张

Java如何利用url下载MP3保存的方法:

1 /** ;

2      * TODO 下载文件到本地 ;

3      * @author nadim  ;

4      * @date Sep 11, 2015 11:45:31 AM ;

5      * @param fileUrl 远程地址 ;

6      * @param fileLocal 本地路径 ;

7      * @throws Exception ;

8      */ ;

9     public void downloadFile(String fileUrl,String fileLocal) throws Exception {;

10         URL url = new URL(fileUrl)

11         HttpURLConnection urlCon = (HttpURLConnection) url.openConnection()

12         urlCon.setConnectTimeout(6000)

13         urlCon.setReadTimeout(6000)

14         int code = urlCon.getResponseCode()

15         if (code != HttpURLConnection.HTTP_OK) {

16             throw new Exception("文件读取失败")

17         }      

18         //读文件流;

19        DataInputStream in = new DataInputStream(urlCon.getInputStream())

20         DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal))

21         byte[] buffer = new byte[2048]

22         int count = 0

23         while ((count = in.read(buffer)) >0) {;

24             out.write(buffer, 0, count)

25         }

26         out.close()

27         in.close()

28     }。

Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。

Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程 。

java编程方法下载服务器上的文件到本地客服端,代码如下:

import java.io.BufferedWriter

import java.io.File

import java.io.FileOutputStream

import java.io.FileWriter

import java.io.IOException

import java.io.InputStream

import java.net.URL

import java.net.URLConnection

 

public class DownLoad {   

 public static void downloadFile(URL theURL, String filePath) throws IOException {  

   File dirFile = new File(filePath)

      if(!dirFile.exists()){ 

        //文件路径不存在时,自动创建目录

        dirFile.mkdir()

      }

  //从服务器上获取图片并保存

     URLConnection connection = theURL.openConnection()

     InputStream in = connection.getInputStream()  

     FileOutputStream os = new FileOutputStream(filePath+"\\123.png") 

     byte[] buffer = new byte[4 * 1024]  

     int read  

     while ((read = in.read(buffer)) > 0) {  

        os.write(buffer, 0, read)  

          }  

       os.close()  

       in.close()

  }   

     public static void main(String[] args) { 

      //下面添加服务器的IP地址和端口,以及要下载的文件路径

      String urlPath = "http://服务器IP地址:端口/image/123.png" 

      

      //下面代码是下载到本地的位置

      String filePath = "d:\\excel" 

  

      URL url = new URL(urlPath) 

  

          try { 

  

             downloadFile(url,filePath) 

  

           } catch (IOException e) { 

  

            e.printStackTrace() 

  

         } 

  

      }   

}

java本身要生成excel文件必然是在后台做的,通过poi库生成excel文件并制作表格。

无法直接通过网页保存生成excel。

至于下载到本地任意位置,也是后台生成了excel文件发送到前台(浏览器),由用户选择要存在哪儿,不能直接存储(这是web沙箱限制,不允许网页直接访问本地硬盘,不然你想想,如果你打开一个网页,网页代码可以任意访问你的硬盘,你还敢开网页吗)。

要绕过沙箱限制必须装插件,也就是,你必须开发一个com或plugin插件,可以访问本地硬盘,但这需要用户手工安装(比如flash的插件,你之所以能用网页看flash是因为装了它的插件,但这是你手工装的,它不能绕过你直接给你装,它必须询问你行不行,你要手工点了OK,才能装)