RandomAccessFile實(shí)現(xiàn)斷點(diǎn)續(xù)傳

本文出自:https://blog.csdn.net/dt235201314/article/details/80911932

一丶概述

斷點(diǎn)續(xù)傳是IO章節(jié)的練習(xí)泌豆,顯然實(shí)現(xiàn)斷點(diǎn)續(xù)傳知識(shí)點(diǎn)不僅僅是IO相關(guān)知識(shí),RandomAccessFile倒是主要環(huán)節(jié)

二丶效果圖

image.png

三丶RandomAccessFile

1.簡介

image

我們可以看到它的父類是Object吏饿,沒有繼承字節(jié)流踪危、字符流家族中任何一個(gè)類蔬浙。并且它實(shí)現(xiàn)了DataInput、DataOutput這兩個(gè)接口贞远,也就意味著這個(gè)類既可以讀也可以寫畴博。

RandomAccessFile既可以讀取文件內(nèi)容,也可以向文件輸出數(shù)據(jù)蓝仲。同時(shí)支持“隨機(jī)訪問”的方式绎晃,可以直接跳轉(zhuǎn)到文件的任意地方來讀寫數(shù)據(jù)。
與OutputStream杂曲、Writer等輸出流不同的是,RandomAccessFile允許自由定義文件記錄指針袁余,RandomAccessFile可以不從開始的地方開始輸出擎勘,因此RandomAccessFile可以向已存在的文件后追加內(nèi)容。如果程序需要向已存在的文件后追加內(nèi)容颖榜,則應(yīng)該使用RandomAccessFile棚饵。
RandomAccessFile的一個(gè)重要使用場景就是網(wǎng)絡(luò)請(qǐng)求中的多線程下載及斷點(diǎn)續(xù)傳。

2.構(gòu)造方法

RandomAccessFile類有兩個(gè)構(gòu)造函數(shù)掩完,其實(shí)這兩個(gè)構(gòu)造函數(shù)基本相同噪漾,只不過是指定文件的形式不同——一個(gè)需要使用String參數(shù)來指定文件名,一個(gè)使用File參數(shù)來指定文件本身且蓬。除此之外欣硼,創(chuàng)建RandomAccessFile對(duì)象時(shí)還需要指定一個(gè)mode參數(shù),該參數(shù)指定RandomAccessFile的訪問模式恶阴,一共有4種模式
"r": 以只讀方式打開诈胜。調(diào)用結(jié)果對(duì)象的任何 write 方法都將導(dǎo)致拋出 IOException。
"rw": 打開以便讀取和寫入冯事。
"rws": 打開以便讀取和寫入焦匈。相對(duì)于 "rw","rws" 還要求對(duì)“文件的內(nèi)容”或“元數(shù)據(jù)”的每個(gè)更新都同步寫入到基礎(chǔ)存儲(chǔ)設(shè)備昵仅。
"rwd" : 打開以便讀取和寫入缓熟,相對(duì)于 "rw","rwd" 還要求對(duì)“文件的內(nèi)容”的每個(gè)更新都同步寫入到基礎(chǔ)存儲(chǔ)設(shè)備摔笤。

3.重要方法

RandomAccessFile對(duì)象包含了一個(gè)記錄指針够滑,用以標(biāo)識(shí)當(dāng)前讀寫處的位置囊颅,當(dāng)程序新創(chuàng)建一個(gè)RandomAccessFile對(duì)象時(shí)皮璧,該對(duì)象的文件指針記錄位于文件頭(也就是0處),當(dāng)讀/寫了n個(gè)字節(jié)后姻锁,文件記錄指針將會(huì)后移n個(gè)字節(jié)寞冯。除此之外渴析,RandomAccessFile還可以自由移動(dòng)該記錄指針晚伙。下面就是RandomAccessFile具有的兩個(gè)特殊方法,來操作記錄指針俭茧,實(shí)現(xiàn)隨機(jī)訪問:
long getFilePointer( ):返回文件記錄指針的當(dāng)前位置

void seek(long pos ):將文件指針定位到pos位置

4.demo案例

public static void main(String[] args)
{
    try
    {
        insert("d:/out.txt",5,"插入的內(nèi)容");
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

private static void insert(String fileName,long pos,String content) throws IOException
{
    //創(chuàng)建臨時(shí)空文件
    File tempFile = File.createTempFile("temp",null);
    //在虛擬機(jī)終止時(shí)咆疗,請(qǐng)求刪除此抽象路徑名表示的文件或目錄
    tempFile.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempFile);

    RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
    raf.seek(pos);
    byte[] buffer = new byte[4];
    int num = 0;
    while(-1 != (num = raf.read(buffer)))
    {
        fos.write(buffer,0,num);
    }
    raf.seek(pos);
    raf.write(content.getBytes());
    FileInputStream fis = new FileInputStream(tempFile);
    while(-1 != (num = fis.read(buffer)))
    {
        raf.write(buffer,0,num);
    }
}  
image

一個(gè)漢字=2個(gè)英文字母=2字節(jié) 杭州G=5個(gè)字節(jié)

四丶斷點(diǎn)續(xù)傳實(shí)現(xiàn)原理

其實(shí)斷點(diǎn)續(xù)傳的原理很簡單,從字面上理解母债,所謂斷點(diǎn)續(xù)傳就是從停止的地方重新下載午磁。
斷點(diǎn):線程停止的位置。
續(xù)傳:從停止的位置重新下載毡们。
用代碼解析就是:
斷點(diǎn) ==> 當(dāng)前線程已經(jīng)下載完成的數(shù)據(jù)長度迅皇。
續(xù)傳 ==> 向服務(wù)器請(qǐng)求上次線程停止位置之后的數(shù)據(jù)。
原理知道了衙熔,功能實(shí)現(xiàn)起來也簡單登颓。每當(dāng)線程停止時(shí)就把已下載的數(shù)據(jù)長度寫入記錄文件,當(dāng)重新下載時(shí)红氯,從記錄文件讀取已經(jīng)下載了的長度框咙。而這個(gè)長度就是所需要的斷點(diǎn)。
續(xù)傳的實(shí)現(xiàn)也簡單痢甘,可以通過設(shè)置網(wǎng)絡(luò)請(qǐng)求參數(shù)喇嘱,請(qǐng)求服務(wù)器從指定的位置開始讀取數(shù)據(jù)。
而要實(shí)現(xiàn)這兩個(gè)功能只需要使用到httpURLconnection里面的setRequestProperty方法便可以實(shí)現(xiàn).

public void setRequestProperty(String field, String newValue)

如下所示塞栅,便是向服務(wù)器請(qǐng)求500-1000之間的500個(gè)byte:

conn.setRequestProperty("Range", "bytes=" + 500 + "-" + 1000);

以上只是續(xù)傳的一部分需求者铜,當(dāng)我們獲取到下載數(shù)據(jù)時(shí),還需要將數(shù)據(jù)寫入文件放椰,而普通發(fā)File對(duì)象并不提供從指定位置寫入數(shù)據(jù)的功能王暗,這個(gè)時(shí)候,就需要使用到RandomAccessFile來實(shí)現(xiàn)從指定位置給文件寫入數(shù)據(jù)的功能庄敛。

public void seek(long offset)

如下所示俗壹,便是從文件的的第100個(gè)byte后開始寫入數(shù)據(jù)。

raFile.seek(100);

而開始寫入數(shù)據(jù)時(shí)還需要用到RandomAccessFile里面的另外一個(gè)方法

public void write(byte[] buffer, int byteOffset, int byteCount)

該方法的使用和OutputStream的write的使用一模一樣...

而多線程斷點(diǎn)續(xù)傳便是在單線程的斷點(diǎn)續(xù)傳上延伸的藻烤,而多線程斷點(diǎn)續(xù)傳是把整個(gè)文件分割成幾個(gè)部分绷雏,每個(gè)部分由一條線程執(zhí)行下載,而每一條下載線程都要實(shí)現(xiàn)斷點(diǎn)續(xù)傳功能怖亭。
為了實(shí)現(xiàn)文件分割功能涎显,我們需要使用到httpURLconnection的另外一個(gè)方法:

public int getContentLength()

當(dāng)請(qǐng)求成功時(shí),可以通過該方法獲取到文件的總長度兴猩。
每一條線程下載大小 = fileLength / THREAD_NUM

在多線程斷點(diǎn)續(xù)傳下載中期吓,有一點(diǎn)需要特別注意:

由于文件是分成多個(gè)部分是被不同的線程的同時(shí)下載的,這就需要倾芝,每一條線程都分別需要有一個(gè)斷點(diǎn)記錄讨勤,和一個(gè)線程完成狀態(tài)的記錄箭跳;

只有所有線程的下載狀態(tài)都處于完成狀態(tài)時(shí),才能表示文件已經(jīng)下載完成潭千。

五丶核心代碼實(shí)現(xiàn)

主Activity

public class DownLoadActivity extends Activity {
    private static final int PROCESSING = 1;
    private static final int FAILURE = -1;

    private EditText pathText;
    private Button downloadButton;
    private Button stopButton;
    private ProgressBar progressBar;
    private Context context;
    Handler handler = new UIHandler(this);

    
    private static class UIHandler extends Handler {
        private final WeakReference<DownLoadActivity> mActivity;

        //弱引用谱姓,避免內(nèi)存泄露
        UIHandler(DownLoadActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            DownLoadActivity activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case PROCESSING:
                        ProgressBar progressBar = (ProgressBar) activity.findViewById(R.id.progressBar);
                        TextView resultView = (TextView) activity.findViewById(R.id.resultView);
                        progressBar.setProgress(msg.getData().getInt("size"));
                        float num = (float) progressBar.getProgress() / (float) progressBar.getMax();
                        int result = (int) (num * 100);
                        resultView.setText(result + "%");
                        if (progressBar.getProgress() == progressBar.getMax()) {
                            Toast.makeText(activity, R.string.success, Toast.LENGTH_LONG).show();
                        }
                        break;
                    case FAILURE:
                        Toast.makeText(activity, R.string.error, Toast.LENGTH_LONG).show();
                        break;
                    default:
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.down_load_activity);
        context = this;
        pathText = (EditText) findViewById(R.id.path);
        downloadButton = (Button) findViewById(R.id.downloadbutton);
        stopButton = (Button) findViewById(R.id.stopbutton);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        ButtonClickListener listener = new ButtonClickListener();
        downloadButton.setOnClickListener(listener);
        stopButton.setOnClickListener(listener);
    }

    private class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.downloadbutton:
                    String path = pathText.getText().toString();
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        //外部存儲(chǔ)
                        //File savDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
                        //File savDir = Environment.getExternalStorageDirectory();
                        //內(nèi)部存儲(chǔ)
                        File savDir = new File(context.getCacheDir(), "/cache/exe");
                        download(path, savDir);
                    } else {
                        Toast.makeText(getApplicationContext(), R.string.sdcarderror, Toast.LENGTH_LONG).show();
                    }
                    downloadButton.setEnabled(false);
                    stopButton.setEnabled(true);
                    break;
                case R.id.stopbutton:
                    exit();
                    Toast.makeText(getApplicationContext(), "Now thread is Stopping!!", Toast.LENGTH_LONG).show();
                    downloadButton.setEnabled(true);
                    stopButton.setEnabled(false);
                    break;
                default:
            }
        }

        private DownloadTask task;

        private void exit() {
            if (task != null) {
                task.exit();
            }
        }

        private void download(String path, File savDir) {
            task = new DownloadTask(path, savDir);
            new Thread(task).start();
        }

        class DownloadTask implements Runnable {
            private String path;
            private File saveDir;
            private FileDownloader loader;

            DownloadTask(String path, File saveDir) {
                this.path = path;
                this.saveDir = saveDir;
            }

            void exit() {
                if (loader != null) {
                    loader.exit();
                }
            }

            //進(jìn)度監(jiān)聽,通過message機(jī)制把傳送進(jìn)度
            DownloadProgressListener downloadProgressListener = new DownloadProgressListener() {
                @Override
                public void onDownloadSize(int size) {
                    Message msg = new Message();
                    msg.what = PROCESSING;
                    msg.getData().putInt("size", size);
                    handler.sendMessage(msg);
                }
            };

            @Override
            public void run() {
                try {
                    //固定三個(gè)線程
                    loader = new FileDownloader(getApplicationContext(), path, saveDir, 3);
                    progressBar.setMax(loader.getFileSize());
                    loader.download(downloadProgressListener);
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendMessage(handler.obtainMessage(FAILURE));
                }
            }
        }
    }
}

下載線程類

public class DownloadThread extends Thread {
    private static final String TAG = "DownloadThread";
    private File saveFile;
    private URL downUrl;
    private int block;
    private int threadId = -1;
    private int downloadedLength;
    private boolean finished = false;
    private FileDownloader downloader;

    DownloadThread(FileDownloader downloader, URL downUrl, File saveFile, int block, int downloadedLength, int threadId) {
        this.downUrl = downUrl;
        this.saveFile = saveFile;
        this.block = block;
        this.downloader = downloader;
        this.threadId = threadId;
        this.downloadedLength = downloadedLength;
    }

    @Override
    public void run() {
        if(downloadedLength < block){
            try {
                HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();
                http.setConnectTimeout(5 * 1000);
                http.setRequestMethod("GET");
                http.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
                http.setRequestProperty("Accept-Language", "zh-CN");
                http.setRequestProperty("Referer", downUrl.toString());
                http.setRequestProperty("Charset", "UTF-8");
                int startPos = block * (threadId - 1) + downloadedLength;
                int endPos = block * threadId -1;
                http.setRequestProperty("Range", "bytes=" + startPos + "-"+ endPos);
                http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
                http.setRequestProperty("Connection", "Keep-Alive");

                InputStream inStream = http.getInputStream();
                byte[] buffer = new byte[1024];
                int offset = 0;
                print("Thread " + this.threadId + " starts to download from position "+ startPos);
                RandomAccessFile threadFile = new RandomAccessFile(this.saveFile, "rwd");
                threadFile.seek(startPos);

                while (!downloader.getExited() && (offset = inStream.read(buffer, 0, 1024)) != -1) {
                    threadFile.write(buffer, 0, offset);
                    downloadedLength += offset;
                    downloader.update(this.threadId, downloadedLength);
                    downloader.append(offset);
                }

                threadFile.close();
                inStream.close();

                if(downloader.getExited())
                    print("Thread " + this.threadId + " has been paused");
                else
                    print("Thread " + this.threadId + " download finish");

                this.finished = true;
            } catch (Exception e) {
                this.downloadedLength = -1;
                print("Thread "+ this.threadId+ ":"+ e);
            }
        }
    }

    private static void print(String msg){
        Log.i(TAG, msg);
    }

    public boolean isFinished() {
        return finished;
    }

    public long getDownloadedLength() {
        return downloadedLength;
    }
}

文件下載類

public class FileDownloader {
    private static final String TAG = "FileDownloader";
    private Context context;
    private FileService fileService;
    private boolean exited;
    private int downloadedSize = 0;
    private int fileSize = 0;
    private DownloadThread[] threads;
    private File saveFile;
    private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();
    private int block;
    private String downloadUrl;

    public int getThreadSize() {
        return threads.length;
    }

    public void exit() {
        this.exited = true;
    }

    public boolean getExited() {
        return this.exited;
    }

    public int getFileSize() {
        return fileSize;
    }

    protected synchronized void append(int size) {
        downloadedSize += size;
    }

    protected synchronized void update(int threadId, int pos) {
        this.data.put(threadId, pos);
        this.fileService.update_tyc(this.downloadUrl, threadId, pos);
        //this.fileService.update(this.downloadUrl, this.data);
    }

    public FileDownloader(Context context, String downloadUrl, File fileSaveDir, int threadNum) {
        try {
            this.context = context;
            this.downloadUrl = downloadUrl;
            fileService = new FileService(this.context);
            URL url = new URL(this.downloadUrl);
            if (!fileSaveDir.exists())
                fileSaveDir.mkdirs();
            this.threads = new DownloadThread[threadNum];

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            conn.setRequestProperty("Accept-Language", "zh-CN");
            conn.setRequestProperty("Referer", downloadUrl);
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.connect();
            printResponseHeader(conn);

            if (conn.getResponseCode() == 200) {
                this.fileSize = conn.getContentLength();
                if (this.fileSize <= 0)
                    throw new RuntimeException("Unkown file size ");

                String filename = getFileName(conn);
                this.saveFile = new File(fileSaveDir, filename);
                Map<Integer, Integer> logdata = fileService.getData(downloadUrl);

                if (logdata.size() > 0) {
                    for (Map.Entry<Integer, Integer> entry : logdata.entrySet())
                        data.put(entry.getKey(), entry.getValue());
                }

                if (this.data.size() == this.threads.length) {
                    for (int i = 0; i < this.threads.length; i++) {
                        this.downloadedSize += this.data.get(i + 1);
                    }
                    print("已經(jīng)下載的長度" + this.downloadedSize + "個(gè)字節(jié)");
                }

                this.block = (this.fileSize % this.threads.length) == 0 ? this.fileSize / this.threads.length : this.fileSize / this.threads.length + 1;
            } else {
                print("服務(wù)器響應(yīng)錯(cuò)誤:" + conn.getResponseCode() + conn.getResponseMessage());
                throw new RuntimeException("server response error ");
            }
        } catch (Exception e) {
            print(e.toString());
            throw new RuntimeException("Can't connection this url");
        }
    }

    private String getFileName(HttpURLConnection conn) {
        String filename = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);

        if (filename == null || "".equals(filename.trim())) {
            for (int i = 0;; i++) {
                String mine = conn.getHeaderField(i);
                if (mine == null)
                    break;
                if ("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase(Locale.getDefault()));
                    if (m.find())
                        return m.group(1);
                }
            }
            filename = UUID.randomUUID() + ".tmp";
        }
        return filename;
    }

    public int download(DownloadProgressListener listener) throws Exception {
        try {
            RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rwd");
            if (this.fileSize > 0)
                randOut.setLength(this.fileSize);
            randOut.close();
            URL url = new URL(this.downloadUrl);

            if (this.data.size() != this.threads.length) {
                this.data.clear();
                for (int i = 0; i < this.threads.length; i++) {
                    this.data.put(i + 1, 0);
                }
                this.downloadedSize = 0;
            }
            for (int i = 0; i < this.threads.length; i++) {
                int downloadedLength = this.data.get(i + 1);
                if (downloadedLength < this.block && this.downloadedSize < this.fileSize) {
                    this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i + 1), i + 1);
                    this.threads[i].setPriority(7);
                    this.threads[i].start();
                } else {
                    this.threads[i] = null;
                }
            }
            this.fileService.delete(this.downloadUrl);
            this.fileService.save(this.downloadUrl, this.data);
            boolean notFinished = true;
            while (notFinished) {
                Thread.sleep(900);
                notFinished = false;
                for (int i = 0; i < this.threads.length; i++) {
                    if (this.threads[i] != null && !this.threads[i].isFinished()) {
                        notFinished = true;
                        if (this.threads[i].getDownloadedLength() == -1) {
                            this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i + 1), i + 1);
                            this.threads[i].setPriority(7);
                            this.threads[i].start();
                        }
                    }
                }
                if (listener != null)
                    listener.onDownloadSize(this.downloadedSize);
            }
            if (downloadedSize == this.fileSize)
                this.fileService.delete(this.downloadUrl);
        } catch (Exception e) {
            print(e.toString());
            throw new Exception("File downloads error");
        }
        return this.downloadedSize;
    }

    public static Map<String, String> getHttpResponseHeader(HttpURLConnection http) {
        Map<String, String> header = new LinkedHashMap<String, String>();
        for (int i = 0;; i++) {
            String mine = http.getHeaderField(i);
            if (mine == null)
                break;
            header.put(http.getHeaderFieldKey(i), mine);
        }
        return header;
    }

    public static void printResponseHeader(HttpURLConnection http) {
        Map<String, String> header = getHttpResponseHeader(http);
        for (Map.Entry<String, String> entry : header.entrySet()) {
            String key = entry.getKey() != null ? entry.getKey() + ":" : "";
            print(key + entry.getValue());
        }
    }

    private static void print(String msg) {
        Log.i(TAG, msg);
    }
}

Android內(nèi)存處理類

public class FileService {
    private DBOpenHelper openHelper;

    public FileService(Context context) {
        openHelper = new DBOpenHelper(context);
    }

    @SuppressLint("UseSparseArrays")
    public Map<Integer, Integer> getData(String path) {
        SQLiteDatabase db = openHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[]{path});
        Map<Integer, Integer> data = new HashMap<Integer, Integer>();
        while (cursor.moveToNext()) {
            data.put(cursor.getInt(0), cursor.getInt(1));
            data.put(cursor.getInt(cursor.getColumnIndexOrThrow("threadid")), cursor.getInt(cursor.getColumnIndexOrThrow("downlength")));
        }
        cursor.close();
        db.close();
        return data;
    }

    public void save(String path, Map<Integer, Integer> map) {
        SQLiteDatabase db = openHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                db.execSQL("insert into filedownlog(downpath, threadid, downlength) values(?,?,?)", new Object[]{path, entry.getKey(), entry.getValue()});
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        db.close();
    }


    public void update_tyc(String path, int threadId, int pos) {
        SQLiteDatabase db = openHelper.getWritableDatabase();
        db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?", new Object[]{pos, path, threadId});
        db.close();
    }

    public void update(String path, Map<Integer, Integer> map) {
        SQLiteDatabase db = openHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?", new Object[]{entry.getValue(), path, entry.getKey()});
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        db.close();
    }

    public void delete(String path) {
        SQLiteDatabase db = openHelper.getWritableDatabase();
        db.execSQL("delete from filedownlog where downpath=?", new Object[]{path});
        db.close();
    }
}

數(shù)據(jù)輔助類

public class DBOpenHelper extends SQLiteOpenHelper {
    private static final String DBNAME = "eric.db";
    private static final int VERSION = 1;

    public DBOpenHelper(Context context) {
        super(context, DBNAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, downlength INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS filedownlog");
        onCreate(db);
    }
}

六丶提升學(xué)習(xí)

這里只是入門簡單的用HttpURLConnection實(shí)現(xiàn)刨晴,現(xiàn)在流行的RxRetrofit大神封裝見

RxRetrofit - 終極封裝 - 深入淺出 & 斷點(diǎn)續(xù)傳

七丶參考文章

深入理解JAVA I/O系列四:RandomAccessFile

Android 多線程斷點(diǎn)續(xù)傳下載

源碼下載:

https://github.com/JinBoy23520/CoderToDeveloperByTCLer

寫在最后微信掃碼提問

如果文章對(duì)你有幫助屉来,歡迎點(diǎn)贊關(guān)注

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市狈癞,隨后出現(xiàn)的幾起案子茄靠,更是在濱河造成了極大的恐慌,老刑警劉巖蝶桶,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嘹黔,死亡現(xiàn)場離奇詭異,居然都是意外死亡莫瞬,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門郭蕉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疼邀,“玉大人,你說我怎么就攤上這事召锈∨哉瘢” “怎么了?”我有些...
    開封第一講書人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵涨岁,是天一觀的道長拐袜。 經(jīng)常有香客問我,道長梢薪,這世上最難降的妖魔是什么蹬铺? 我笑而不...
    開封第一講書人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮秉撇,結(jié)果婚禮上甜攀,老公的妹妹穿的比我還像新娘。我一直安慰自己琐馆,他們只是感情好规阀,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著瘦麸,像睡著了一般谁撼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上滋饲,一...
    開封第一講書人閱讀 52,268評(píng)論 1 309
  • 那天厉碟,我揣著相機(jī)與錄音喊巍,去河邊找鬼。 笑死墨榄,一個(gè)胖子當(dāng)著我的面吹牛玄糟,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播袄秩,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼阵翎,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了之剧?” 一聲冷哼從身側(cè)響起郭卫,我...
    開封第一講書人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎背稼,沒想到半個(gè)月后贰军,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蟹肘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年词疼,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片帘腹。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡贰盗,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出阳欲,到底是詐尸還是另有隱情舵盈,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布球化,位于F島的核電站秽晚,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏筒愚。R本人自食惡果不足惜赴蝇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望巢掺。 院中可真熱鬧扯再,春花似錦、人聲如沸址遇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽倔约。三九已至秃殉,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背钾军。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來泰國打工鳄袍, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人吏恭。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓拗小,卻偏偏與公主長得像,于是被迫代替她去往敵國和親樱哼。 傳聞我的和親對(duì)象是個(gè)殘疾皇子哀九,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,111評(píng)論 1 32
  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 29,416評(píng)論 8 265
  • 圖片來自網(wǎng)絡(luò) 聽媽媽說,我開口說話早搅幅,六個(gè)月就會(huì)說了阅束,說的第一句話是“姥——”。 那時(shí)茄唐,媽媽懷里抱著小小的我息裸,翻過...
    鄭十三豆閱讀 370評(píng)論 0 1
  • 這是一個(gè)偉大的時(shí)代 心中的記憶永不磨滅 憶兒時(shí)青蔥歲月 真叫人歡天喜地 念豆蔻青澀年華 正情思紛紛揚(yáng)揚(yáng) 蕩少年激...
    大大的王帥帥閱讀 151評(píng)論 0 3