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语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程 。
ublic HttpServletResponse download(String path, HttpServletResponse response) {try {
// path是指欲下载的文件的路径。
File file = new File(path)
// 取得文件名。
String filename = file.getName()
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase()
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path))
byte[] buffer = new byte[fis.available()]
fis.read(buffer)
fis.close()
// 清空response
response.reset()
// 设置response的Header
response.addHeader("Content-Disposition", "attachmentfilename=" + new String(filename.getBytes()))
response.addHeader("Content-Length", "" + file.length())
OutputStream toClient = new BufferedOutputStream(response.getOutputStream())
response.setContentType("application/octet-stream")
toClient.write(buffer)
toClient.flush()
toClient.close()
} catch (IOException ex) {
ex.printStackTrace()
}
return response
}
java本身要生成excel文件必然是在后台做的,通过poi库生成excel文件并制作表格。无法直接通过网页保存生成excel。
至于下载到本地任意位置,也是后台生成了excel文件发送到前台(浏览器),由用户选择要存在哪儿,不能直接存储(这是web沙箱限制,不允许网页直接访问本地硬盘,不然你想想,如果你打开一个网页,网页代码可以任意访问你的硬盘,你还敢开网页吗)。
要绕过沙箱限制必须装插件,也就是,你必须开发一个com或plugin插件,可以访问本地硬盘,但这需要用户手工安装(比如flash的插件,你之所以能用网页看flash是因为装了它的插件,但这是你手工装的,它不能绕过你直接给你装,它必须询问你行不行,你要手工点了OK,才能装)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)