/** * 从网络加载分段信息 * * @param file * @param url */ private void createBlockFromNetFile(DownloadFile file, URL url) throws CreateBlockException { if (url == null) { throw new CreateBlockException(); // return; } try { // 分段 final int threadCount = Constants.thread_count; blocks.clear(); // HttpURLConnection c = (HttpURLConnection) url.openConnection(); Utils.configCommonHeader(c, file.getSourceUrl()); c.connect(); // if (c.getResponseCode() == 200) { file.setFileSize(c.getContentLength()); } else { throw new CreateBlockException(); // return; } long perBlockSize = file.getFileSize() / threadCount; String filename = getFileName(c, file.getSourceUrl()); file.setFileName(filename); recorder.updateFile(context, file); // File outFile = file.getFile(); if (outFile != null && !outFile.exists()) { outFile.createNewFile(); } // RandomAccessFile randOut = new RandomAccessFile(outFile, // "rw"); // randOut.setLength(file.getFileSize()); // int lastThread = threadCount - 1; final String sourceUrl = file.getSourceUrl(); for (int i = 0; i < threadCount; i++) { long start = i * perBlockSize; long end; if (i == lastThread) { end = file.getFileSize(); } else { end = (i + 1) * perBlockSize; } DownloadBlock b = new DownloadBlock(file, sourceUrl, start, end, 0); blocks.add(b); } // 保存分段记录到数据库 if (!blocks.isEmpty()) { recorder.addBlocks(context, blocks, file.getSourceUrl()); } } catch (IOException e) { e.printStackTrace(); blocks.clear(); throw new CreateBlockException(); } }