fatchfile.java

来自「关于多线程下载的功能实现源代码」· Java 代码 · 共 71 行

JAVA
71
字号
package group.common.globalget.model;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;

public class FatchFile {
	private String urlstr;

	private URL url;

	private URLConnection conn;

	private long pos;

	// private byte[] buff;

	public FatchFile(String urlstr) {
		this.urlstr = urlstr;
		try {
			url = new URL(urlstr);
			conn = url.openConnection();
			conn.setDoOutput(true);
			conn.connect();
		} catch (Exception e) {
			// TODO: handle exception
		}
		//
		pos = 0;
		download();
		//System.out.println(getFileName()); 
		System.out.println("下载完成");
	}
	
	private String getFileName(){
		String fileName=null;
		int begin=urlstr.lastIndexOf("/");
		fileName = urlstr.substring(begin+1);
		return fileName;
	}

	private void download() {
		try {
			byte[] buff = new byte[1024];
			int len = 0;
			InputStream is = conn.getInputStream();
			String filename= getFileName();
			if (filename==null) {
				System.out.println("没有指明要下载的文件!");
				System.exit(-1);
			}
			RandomAccessFile file = new RandomAccessFile(filename, "rw");
			file.seek(pos);
			while ((len = is.read(buff)) != -1) {
				file.write(buff, 0, len);
			}
			file.close();
			is.close();
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void main(String[] args) {
		FatchFile ff = new FatchFile("http://server/data/os.VOB");
		
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?