Bre*_*all 12 java download httpurlconnection
我想得到一些建议,我已经开始了一个新项目来创建一个将使用多个连接的java下载加速器.我想知道如何最好地解决这个问题.
到目前为止,我已经发现我可以使用HttpUrlConnection并使用range属性,但想知道这样做的有效方法.一旦我从多个连接下载了部件,我就必须加入这些部件,以便我们最终得到一个完全下载的文件.
提前致谢 :)
小智 11
myfile.part1, myfile.part2,...我尝试了以下代码来获取内容长度:
public Downloader(String path) throws IOException {
int len = 0;
URL url = new URL(path);
URLConnection connectUrl = url.openConnection();
System.out.println(len = connectUrl.getContentLength());
System.out.println(connectUrl.getContentType());
InputStream input = connectUrl.getInputStream();
int i = len;
int c = 0;
System.out.println("=== Content ===");
while (((c = input.read()) != -1) && (--i > 0)) {
System.out.print((char) c);
}
input.close();
}
Run Code Online (Sandbox Code Playgroud)
这是一个加入文件的示例代码:
public void join(String FilePath) {
long leninfile=0, leng=0;
int count=1, data=0;
try {
File filename = new File(FilePath);
RandomAccessFile outfile = new RandomAccessFile(filename,"rw");
while(true) {
filename = new File(FilePath + count + ".sp");
if (filename.exists()) {
RandomAccessFile infile = new RandomAccessFile(filename,"r");
data=infile.read();
while(data != -1) {
outfile.write(data);
data=infile.read();
}
leng++;
infile.close();
count++;
} else break;
}
outfile.close();
} catch(Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想在下载后避免加入细分,可以使用FileChannel.
使用a FileChannel,您可以写入文件的任何位置(即使有多个线程).
因此,您可以先分配整个文件,然后
在它们进入时写下它们所属的段.
有关详细信息,请参阅Javadocs页面.
| 归档时间: |
|
| 查看次数: |
6488 次 |
| 最近记录: |