案例:下载工具
一、DownLoadJFrame1.java
package util;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class DownLoadJFrame1 extends JFrame implements ActionListener{
// 声明组件
private JLabel loadJLable;
private JTextField loadJTextField;
private JButton lodeJButton;
//随机文件
private RandomAccessFile accessFile;
public DownLoadJFrame1() {
//设置标题
super("下载工具");
//设置大小
this.setSize(400,300);
//设置居中
this.setLocationRelativeTo(null);
//关闭
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置可见性
this.setVisible(true);
//设置容器对象
Container c=this.getContentPane();
//设置容器面板
c.setLayout(null);
//实例化组件
loadJLable=new JLabel("下载的地址");
loadJTextField=new JTextField("http://localhost:8080/day31/image/ff.jpg");
lodeJButton=new JButton("下载");
//设置组件位置
loadJLable.setBounds(10,20,80,30);
loadJTextField.setBounds(90,20,280,30);
lodeJButton.setBounds(120,100,100,30);
//添加到面板
c.add(loadJLable);
c.add(loadJTextField);
c.add(lodeJButton);
//添加监听事件
lodeJButton.addActionListener(this);
}
public static void main(String[] args) {
new DownLoadJFrame1();
}
@Override
public void actionPerformed(ActionEvent e) {
lodeJButton.setEnabled(false);
//获取下载的路径
final String path=loadJTextField.getText();
try {
//根据路径创建URL对象
URL url=new URL(path);
//打开连接
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
//设置请求方式
httpURLConnection.setRequestMethod("GET");
//设置连接的超时时间
httpURLConnection.setConnectTimeout(5000);
//设置请求的头信息
httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20100101 Firefox/21.0");
//获取下载的文件大小
int size=httpURLConnection.getContentLength();
//根据下载文件的名称 设置本地保存的文件
File file=new File("E:"+path.substring(path.lastIndexOf("/")));
//根据文件创建出对象
accessFile=new RandomAccessFile(file, "rw");
//设置大小
accessFile.setLength(size);
//释放资源
accessFile.close();
httpURLConnection.disconnect();
//定义线程的数据量
int threadNum=3;
//往里边写数据
for (int i = 1; i < threadNum; i++) {
//计算出每个线程下载的平均量(大小)
int blockSize=size/threadNum;
//计算机每个线程的开始下载的位置
final int startSize=(i-1)*blockSize;
int temp=i*blockSize-1;
if (i==threadNum) {
if (temp<size) {
temp=size;
}
}
//计算出每个线程下载的结束位置
final int endSize=temp;
//文件随机读取的对象
final RandomAccessFile threadFile=new RandomAccessFile(file,"rw");
//创建线程
new Thread(){
public void run() {
try {
//根据路径创建URL对象
URL url=new URL(path);
//打开连接
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
//设置请求方式
httpURLConnection.setRequestMethod("GET");
//设置连接的超时时间
httpURLConnection.setConnectTimeout(5000);
//设置请求的头信息
httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20100101 Firefox/21.0");
System.out.println(Thread.currentThread().getName()+"从--"+startSize+"---开始下载,到"+endSize+"结束");
//设置读取的range的范围
httpURLConnection.setRequestProperty("Range","bytes="+startSize+"-"+endSize);
//获取输入流对象
InputStream is=httpURLConnection.getInputStream();
//设置文件开始写入的位置
threadFile.seek(startSize);
//缓冲区
byte buffer[]=new byte[1024];
//读取长度
int len=0;
while((len=is.read(buffer))!=-1){
//写入
threadFile.write(buffer,0,len);
}
//释放资源
is.close();
threadFile.close();
httpURLConnection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
//写文件
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
DownLoadJFrames2.java
package util;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class DownLoadJFrames2 extends JFrame {
// 声明组件
private JLabel downlodeJlable;
private JTextField downlodeJTextField;
private JButton downlodeJButton;
private JLabel threadNumJable;
private JTextField threadNumJTextField;
private JProgressBar downlodeJProgressBar;
public DownLoadJFrames2() {
super("下载工具");
// 设置大小
this.setSize(400, 300);
// 设置居中显示
this.setLocationRelativeTo(null);
// 设置窗体关闭即退出程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 可见性
this.setVisible(true);
// 获取容器对象
Container c = this.getContentPane();
// 设置容器面板布局为null
c.setLayout(null);
// 实例化组件
downlodeJlable = new JLabel("下载的地址");
downlodeJTextField = new JTextField(
"http://localhost:8080/day31/image/ff.jpg");
downlodeJButton = new JButton("下载");
threadNumJable=new JLabel("开启线程数");
threadNumJTextField=new JTextField("3");
downlodeJProgressBar=new JProgressBar();
// 设置组件的位置
downlodeJlable.setBounds(10, 20, 80, 30);
downlodeJTextField.setBounds(95, 20, 280, 30);
threadNumJable.setBounds(10,60,80,30);
threadNumJTextField.setBounds(95,60,280, 30);
downlodeJProgressBar.setBounds(10,100,360, 10);
downlodeJButton.setBounds(120, 120, 100, 30);
// 添加到面板中
c.add(downlodeJButton);
c.add(downlodeJTextField);
c.add(downlodeJlable);
c.add(threadNumJTextField);
c.add(threadNumJable);
c.add(downlodeJProgressBar);
// 添加点击事件
downlodeJButton.addActionListener(new MyActionListener());
}
/**
* 内部类
*
* @param args
*/
class MyActionListener implements ActionListener {
// 随机文件
private RandomAccessFile accessFile;
@Override
public void actionPerformed(ActionEvent e) {
downlodeJButton.setEnabled(false);
// 获取下载的路径
String path = downlodeJTextField.getText();
String txThreadNun=threadNumJTextField.getText();
try {
// 根据路径创建URL对象
URL url = new URL(path);
// 打开连接
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 设置请求的方式
httpURLConnection.setRequestMethod("GET");
// 设置连接的超时时间
httpURLConnection.setConnectTimeout(5000);
// 设置请求的头信息
httpURLConnection
.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20100101 Firefox/21.0");
//获取状态码
int startusCode=httpURLConnection.getResponseCode();
//是否响应成功的判断
if (startusCode==200) {
//获取下载的文件大小
int size=httpURLConnection.getContentLength();
//根据下载文件的名称 设置本地保存的文件
File file=new File("E:"+path.substring(path.lastIndexOf("/")));
//根据文件创建出RandomAccessFile对象
accessFile=new RandomAccessFile(file,"rw");
//设置文件大小
accessFile.setLength(size);
//设置进度条大小
downlodeJProgressBar.setMaximum(size);
downlodeJProgressBar.setValue(0);
accessFile.close();
httpURLConnection.disconnect();
//定义线程的数据量
int threadNum=Integer.parseInt(txThreadNun);
//往里边写数据
for (int i = 1; i <=threadNum; i++) {
//计算出每个线程下载的平均量(大小)
int blockSize=size/threadNum;
//计算出每个线程的开始下载的位置
int startSize=(i-1)*blockSize;
//计算出每个线程下载的结束位置
int endSize=i*blockSize-1;
if (i==threadNum) {
if (endSize<size) {
endSize=size;
}
}
//文件随机读取的对象
RandomAccessFile threadFile=new RandomAccessFile(file, "rw");
new DownLodeThread(path, startSize, endSize, threadFile, downlodeJProgressBar).start();
//写文件
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
new DownLoadJFrames2();
}
}
工具包DownLodeThread.java
package util;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class DownLodeThread extends Thread {
// 下载的路径
private String path;
// 开始位置
private int startSize;
// 结束位置
private int endSize;
// 随机读取文件的对象
private RandomAccessFile threadFile;
// 实例化
public DownLodeThread(String path, int startSize, int endSize,
RandomAccessFile threadFile) {
super();
this.path = path;
this.startSize = startSize;
this.endSize = endSize;
this.threadFile = threadFile;
}
@Override
public void run() {
try {
// 根据路径创建URL对象
URL url = new URL(path);
// 打开连接
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 设置请求的方式
httpURLConnection.setRequestMethod("GET");
// 设置连接的超时时间
httpURLConnection.setConnectTimeout(5000);
// 设置请求的头信息
httpURLConnection
.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20100101 Firefox/21.0");
System.out.println(Thread.currentThread().getName() + "从--"
+ startSize + "---开始下载,到" + endSize + "结束");
// 设置你读取的range的范围
httpURLConnection.setRequestProperty("Range", "bytes=" + startSize
+ "-" + endSize);
// 获取输入流对象
InputStream is = httpURLConnection.getInputStream();
// 设置文件开始写入的位置
threadFile.seek(startSize);
// 缓冲区
byte buffer[] = new byte[1024];
// 读取的长度
int len = 0;
// 读取
while ((len = is.read(buffer)) != -1) {
// 写入
threadFile.write(buffer, 0, len);
}
// 释放资源
is.close();
threadFile.close();
httpURLConnection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二、怎样查询AVI("video/x-msvideo")的类型
用枚举类FileType.java
package util;
/**
* 枚举
* @author yanmei
*
*/
public enum FileType {
/**
* type <mime-mapping> <extension>avi</extension>
* <mime-type>video/x-msvideo</mime-type> </mime-mapping>
*/
AVI("video/x-msvideo");
private String value;
private FileType(String value){
this.value=value;
}
public String getValue(){
return value;
}
public static FileType FindByValue(String value){
FileType fileType=null;
FileType types[]=FileType.values();
for(FileType type:types){
if (type.getValue().equals(value)) {
fileType=type;
break;
}
}
return fileType;
}
}
测试类FileTest.java
package util;
import static org.junit.Assert.*;
import org.junit.Test;
public class FileTest {
@Test
public void test() {
FileType fileType=FileType.FindByValue("video/x-msvideo");
System.out.println(fileType.name());
}
}