首页 > 代码库 > Java实现的一个简单的下载器

Java实现的一个简单的下载器

package com.shawearn.download;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;http://www.huiyi8.com/jiaoben/
import java.io.FileNotFoundException; JQuery特效
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class ShawDown {
// static String source = "http://www.baidu.com/img/bdlogo.gif";
// static String source = "http://down.sandai.net/mini/Minithunder_dl1.5.3.288.exe";
static String source = "http://img15.poco.cn/mypoco/myphoto/20140402/16/52430825201404021616531582238826629_002.jpg";
String fileName = null;
URL url = null;
InputStream inputStream = null;
URLConnection con = null;
public static void main(String[] args) {
ShawDown shawDown = new ShawDown();
shawDown.setFileName(source);
shawDown.connection();
shawDown.creatFile();
shawDown.writeResult();
//连接
public void connection() {
try {
url = new URL(source);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
con = url.openConnection();
// con.setConnectTimeout(1000 * 60 *30);
// con.setReadTimeout(1000 * 60 *30);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//创建本地文件
public void creatFile() {
file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//将从网络获取的文件的InputStream并写入到本地
private void writeResult() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
BufferedOutputStream bos = new BufferedOutputStream(fos);
// BufferedOutputStream bos = new BufferedOutputStream(fos, 300 * 1024);
dos = new DataOutputStream(bos);
try {
// is = con.getOutputStream();
inputStream = con.getInputStream();
// System.out.println(inputStream.hashCode());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
BufferedInputStream bis = new BufferedInputStream(inputStream);
// BufferedInputStream bis = new BufferedInputStream(inputStream,
// 300 * 1024);
DataInputStream dis = new DataInputStream(bis);
try {
while (true) {
dos.write(dis.readByte());
} catch (EOFException e) {
System.out.println("下载完成!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
dos.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();