本文目录一览:
java 如何实现下载功能
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URL;
import java.util.Random;
/**
* 实现了下载的功能
*/
public class SimpleTh {
public static void main(String[] args) {
// TODO Auto-generated method stub
// String path = "倩女幽魂.mp3";//MP3下载的地址
String path = "";
try {
new SimpleTh().download(path, 3); // 对象调用下载的方法
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getFilename(String path) { // 获得文件的名字
return path.substring(path.lastIndexOf('/') + 1);
}
public void download(String path, int threadsize) throws Exception { // 下载的方法
// 参数 下载地址,线程数量
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 获取HttpURLConnection对象
conn.setRequestMethod("GET"); // 设置请求格式,这里是GET格式
conn.setReadTimeout(5 * 1000);
int filelength = conn.getContentLength(); // 获取要下载文件的长度
String filename = getFilename(path);
File saveFile = new File(filename);
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.setLength(filelength);
accessFile.close();
int block = filelength % threadsize == 0 ? filelength / threadsize : filelength / threadsize + 1;
for (int threadid = 0; threadid <= threadsize; threadid++) {
new DownloadThread(url, saveFile, block, threadid).start();
}
}
private final class DownloadThread extends Thread {
private URL url;
private File saveFile;
private int block; // 每条线程下载的长度
private int threadid; // 线程id
public DownloadThread(URL url, File saveFile, int block, int threadid) {
this.url = url;
this.saveFile = saveFile;
this.block = block;
this.threadid = threadid;
}
@Override
public void run() {
// 计算开始位置的公式:线程id*每条线程下载的长度=?
// 计算结束位置的公式:(线程id+1)*每条线程下载数据长度-1=?
int startposition = threadid * block;
int endposition = (threadid + 1) * block - 1;
try {
try {
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.seek(startposition); // 设置从什么位置写入数据
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
conn.setRequestProperty("Range", "bytes= " + startposition + "-" + endposition);
InputStream inStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
accessFile.write(buffer, 0, len);
}
inStream.close();
accessFile.close();
System.out.println("线程id:" + threadid + "下载完成");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
参考一下这个代码。
java怎样实现数据下载功能呢
这是我以前弄的一个下载的模块,里面的pl指的是System.out.println(), 详情可以看 ;tid=156
package com.jc.download;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import static com.jc.tool.io.Out.pl;
public class DownloadThread extends Thread {
private String url = null;
private String file = null;
private long offset = 0;
private long length = 0;
private int no = 0;
public DownloadThread(String url, String file, long offset, long length) {
pl("正在初始化下载线程...");
this.url = url;
this.file = file;
this.offset = offset;
this.length = length;
}
public void setNo(int no) {
this.no = no;
}
@Override
public void run() {
try {
pl("线程【" + no + "】开始连接主机...");
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
pl("线程【" + no + "】发送下载请求...");
conn.setRequestMethod("GET");
conn.setRequestProperty("RANGE", "bytes=" + this.offset + "-"
+ (this.offset + this.length - 1));
pl("线程【" + no + "】创建文件流...");
BufferedInputStream bis = new BufferedInputStream(
conn.getInputStream());
byte[] buf = new byte[1024];
int bytesRead;
pl("线程【" + no + "】开始向文件写入数据...");
while ((bytesRead = bis.read(buf, 0, buf.length)) != -1) {
this.writeFile(file, offset, buf, bytesRead);
this.offset += bytesRead;
}
pl("线程【" + no + "】写入完成");
} catch (IOException e) {
e.printStackTrace();
}
pl("线程【" + no + "】退出");
}
public void writeFile(String fileName, long offset, byte[] bytes,
int realLength) throws IOException {
File file = new File(fileName);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(offset);
raf.write(bytes, 0, realLength);
raf.close();
}
}
怎样编一个能实现文件下载功能的JAVA程序
java实现文件下载 一、采用RequestDispatcher的方式进行
- web.xml文件中增加
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
- 程序如下:
<%@ page language="java" import="java.net.*" pageEncoding="gb2312"%>
<%
response.setContentType("application/x-download"); // 设置为下载application/x-download
String filenamedownload = "/系统解决方案.doc"; // 即将下载的文件的相对路径
String filenamedisplay = "系统解决方案.doc"; // 下载文件时显示的文件保存名称
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + filenamedisplay);
try {
RequestDispatcher dispatcher = application.getRequestDispatcher(filenamedownload);
if (dispatcher != null) {
dispatcher.forward(request, response);
}
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
%>
二、采用文件流输出的方式下载
- web.xml文件中增加
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
- 程序如下:
<%@ page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%>
<%
// 关于文件下载时采用文件流输出的方式处理:
// 加上response.reset(),并且所有的%后面不要换行,包括最后一个;
// 因为Application Server在处理编译jsp时对于%和%之间的内容一般是原样输出,而且默认是PrintWriter,
// 而你却要进行流输出:ServletOutputStream,这样做相当于试图在Servlet中使用两种输出机制,
// 就会发生:getOutputStream() has already been called for this response的错误
// 详细请见《More Java Pitfill》一书的第二部分 Web层Item 33:试图在Servlet中使用两种输出机制 270
// 而且如果有换行,对于文本文件没有什么问题,但是对于其它格式,比如AutoCAD、Word、Excel等文件
// 下载下来的文件中就会多出一些换行符0x0d和0x0a,这样可能导致某些格式的文件无法打开,有些也可以正常打开。
response.reset(); // 可以加也可以不加
response.setContentType("application/x-download"); // 设置为下载application/x-download
// /../../退WEB-INF/classes两级到应用的根目录下去,注意Tomcat与WebLogic下面这一句得到的路径不同,WebLogic中路径最后没有/
System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "/../../系统解决方案.doc";
String filenamedisplay = "系统解决方案.doc"; // 系统解决方案.txt
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + filenamedisplay);
OutputStream output = null;
FileInputStream fis = null;
try {
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
output.write(b, 0, i);
}
output.flush();
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {
if (fis != null) {
%>
Java如何利用url下载MP3保存到本地?
Java如何利用url下载MP3保存的方法:
/**
* TODO 下载文件到本地
* @author nadim
* @date Sep 11, 2015 11:45:31 AM
* @param fileUrl 远程地址
* @param fileLocal 本地路径
* @throws Exception
*/
public void downloadFile(String fileUrl, String fileLocal) throws Exception {
URL url = new URL(fileUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setConnectTimeout(6000);
urlCon.setReadTimeout(6000);
int code = urlCon.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("文件读取失败");
}
// 读文件流
DataInputStream in = new DataInputStream(urlCon.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
byte[] buffer = new byte[2048];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
}
Java是一门面向对象编程语言,不仅吸收了C语言的各种优点,还摒弃了C里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。 Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程 。
java下载功能实现
楼主得在后台的控制器中用reponse的输出流转化一下,我给你个例子。
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"ISO-8859-1"));
response.addHeader("Content-Length", "" + excelFile.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
求采纳为满意回答。