问题描述
- 为什么使用Java多线程下载文件时下载后的文件和服务器端文件大小一模一样但是无法打开
-
为什么使用Java多线程下载文件时下载后的文件和服务器端文件大小一模一样但是无法打开??package com.miuitust.mutilethread; import java.io.File; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; public class MutileThreadDownload { private static int THREADCOUNT = 3; private static long blocksize; public static void main(String[] args) throws Exception { // 服务器文件路径 String path = "http://localhost/demo.exe"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); if (code == 200) { long size = conn.getContentLength(); System.out.println("服务器文件的大小:" + size); blocksize = size / THREADCOUNT; //在本地创建一个空白的文件 File file = new File("target.exe"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.setLength(size); //20,796,344 20,796,344 //开启线程 for (int i = 1; i <= THREADCOUNT; i++) { long startIndex = (i - 1) * blocksize; long endIndex = i * blocksize - 1; if (i == THREADCOUNT) { endIndex = size-1; } System.out.println("开启线程:" + i + "下载的位置:" + startIndex + "~" + endIndex); new DownloadThread(i, startIndex, endIndex, path).start(); } } conn.disconnect(); } private static class DownloadThread extends Thread { private int threadId; private long startIndex; private long endIndex; private String path; public DownloadThread(int threadId, long startIndex, long endIndex, String path) { super(); this.path = path; this.threadId = threadId; this.startIndex = startIndex; this.endIndex = endIndex; } @Override public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); System.out.println("服务器状态码:" + code); InputStream is = conn.getInputStream(); File file = new File("target.exe"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); //指定文件开始写的位置 raf.seek(startIndex); System.out.println("第" + threadId + "个线程写文件的开始位置:" + startIndex); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1 && startIndex < endIndex) { raf.write(buffer, 0, len); } is.close(); raf.close(); System.out.println("线程" + threadId + "下载完毕了"); } catch (Exception e) { e.printStackTrace(); } } } }
有没有大神晓得是怎么回事呢?
解决方案
用ultraedit之类的工具打开看看内容是不是一样
解决方案二:
不懂帮猜,会不会是下载的文件 编码 和源文件不一致?
解决方案三:
很简单,你根本没下载到文件,而是只是指定了文件的大小和原文件一样大,就是所谓的占位,你这是分段下载文件,响应码改成206就可以了
时间: 2025-01-30 08:46:54