单线程下载网络资源

前几天写了个下载网络资源的类,甩上来懒得解释了.

注意

这其中需要注意的便是保存到本地的文件路径:

windows注意:

例如–>C:\\[单右斜线在Java中有特殊意义,因此路径须写两个右斜线,并且必须以’\\’结尾]
示例:D:\\tmp\\

Linux注意:

根路径是从’/’开始,而且路径必须以’/’结尾.
示例:/usr/local/tmp/

java标志
image-1788

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;

/**
 * 单线程下载.
 *
 * @author Ruidong_pu
 * @version 2013.5.4
 */

public class Download {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // http://xunlei.down.chinaz.com/201302/wordpress-3.5.1-zh_CN.tar.gz 示例地址.
        System.out.println("---->请输入需要下载的URL地址('可以是:http[s],ftp,file'):");
        String fileURL = sc.next();
        System.out.println("---->设置下载文件存放地址:" + "\n---------------------------"
                + "\nwindows注意:"
                + "\n'例如-->C:\\[单右斜线在Java中有特殊意义,因此路径须写两个右斜线,并且必须以'\'结尾]'"
                + "\n示例:D:\\tmp\" + "\n---------------------------"
                + "\nLinux注意:" + "\n根路径是从'/'开始,而且路径必须以'/'结尾."
                + "\n示例:/usr/local/tmp/" + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        String fileAddress = sc.next();
        URL url = null;
        RandomAccessFile raf = null;
        InputStream is = null;
        try {
            url = new URL(fileURL);
            raf = new RandomAccessFile(fileAddress + getFileAddress(url), "rw");
            System.out.println("文件长度:" + getFileLength(url));
            int hasRead = 0;
            is = url.openStream();
            byte[] buff = new byte[1024];
            while ((hasRead = is.read(buff)) > 0) {
                raf.write(buff, 0, hasRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                System.out.println("下载完成!文件名是:" + getFileAddress(url)
                        + ",文件大小:" + getFileLength(url));
                raf.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件长度.
     *
     * @param url
     * @return 文件长度
     * @throws IOException
     */
    private static long getFileLength(URL url) throws IOException {
        return url.openConnection().getContentLengthLong();
    }

    /**
     * 获取文件后缀名.
     *
     * @param url
     * @return 资源名称.
     */
    private static String getFileAddress(URL url) {
        String FileName = url.getPath();
        int index = FileName.lastIndexOf("/");
        return FileName.substring((index + 1), FileName.length());
    }

}