rt
解决方案 »
- 有关synchronized一些问题
- 救命呀java.sql.SQLException: Io 异常: The Network Adapter could not establish the connection
- 高分紧急求助:eclipse插件安装就没成功过...神啊!救救我吧!
- 南京发展有几个问题想请教;
- 请教高手:如何在Applet中获得MAC地址
- 请帮助Java初学者——1、如何调用API解解ARG压缩文件;2、如何用API调用DOS命令!
- 还是applet的socket的问题,请多指教。
- 学了语法,接下来?
- 寻找包包...(请各位关注,谢~)
- 关于outofmemory的问题,请高手赐教
- 求最完美的DBConnection类
- 这个源程序中的Leaf increment()方法是什么
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ThreadDownload implements Runnable {
private URL url;
private File file;
private int offset;
private int len;
private String net;
private InputStream in;
private RandomAccessFile random;
private HttpURLConnection httpConnection;
@Override
public void run() {
StartDownload();
}
public ThreadDownload(String net,File file,int offset,int len)
{
this.net=net;
this.file=file;
this.offset=offset;
this.len=len;
}
public void StartDownload()
{
long start = System.currentTimeMillis();
int byteread=0;
System.out.println("begin to download the file");
System.out.println("the offset is "+offset);
byte[] b=new byte[1024];
try {
url=new URL(net);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
httpConnection=(HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("RANGE","bytes=" + offset + "-");
in=httpConnection.getInputStream();
random = new RandomAccessFile(file,"rw");
random.seek(offset);
while(in.read(b)!=-1&&byteread<=len)
{
random.write(b);
byteread+=b.length;
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("this thread is complete");
long end= System.currentTimeMillis();
System.out.println(end-start);
}
}
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;public class b { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ThreadDownload[] d= new ThreadDownload[4];
Thread[] thread=new Thread[4];
File file = new File("4.mp3");
String net ="http://224.cachefile7.rayfile.com/a8c6/zh-cn/preview/e58932fb329b88afe7f4bbe252f70012/preview.mp3";
URL url=new URL(net);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
int length=http.getContentLength();
System.out.println(length/4);
System.out.println(http.getContentType());
d[0]=new ThreadDownload(net, file, length*0, length/4);
d[1]= new ThreadDownload(net,file,length/4,length/4);
d[2]= new ThreadDownload(net,file,length/2,length/4);
d[3]= new ThreadDownload(net,file,length/4*3,length/4);
for(int i=0;i<4;i++){
thread[i]=new Thread(d[i]);
thread[i].start();
}
}
}
实验的代码 能改一下么
在写之前,先获得要写入数据位置的lock.这样别人就动不了这块地方了.
写完之后unlock.接口就在RandomAccessFile里,lz自己找找吧:)