Downloading Single and Multiple Remote Files with ZIP Compression to Local Storage

Downlaoding Individual Remote Files

The following example demonstrates how to download a single remote file:

public static void main(String[] args) throws IOException {
    URL targetUrl = new URL("http://yingufile-private.oss-cn-beijing.aliyuncs.com/PHYY/jpg/20170628/a85ab00c645e4b89dc38f3b8bb63a4f3");
    HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
    
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod("GET");
    
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Charset", "UTF-8");
    
    byte[] downloadedData = streamToByteArray(connection.getInputStream());
    saveByteArrayToFile(downloadedData, "D://333.png");
    System.out.println(downloadedData.length + " bytes downloaded");
}

public static final byte[] streamToByteArray(InputStream inputStream) throws IOException {
    ByteArrayOutputStream bufferStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[100];
    int bytesRead;
    
    while ((bytesRead = inputStream.read(buffer, 0, 100)) > 0) {
        bufferStream.write(buffer, 0, bytesRead);
    }
    
    return bufferStream.toByteArray();
}

public static File saveByteArrayToFile(byte[] data, String outputPath) {
    File targetFile = null;
    FileOutputStream fileStream = null;

    try {
        targetFile = new File(outputPath);
        fileStream = new FileOutputStream(targetFile);
        fileStream.write(data);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (fileStream != null) {
                fileStream.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    return targetFile;
}

Compressing Multiple Remote Files into ZIP Archive

For recursive compression functionlaity, refer to external resources for implementation patterns.

Integrated implementation for handling multipel files:

String[] fileIdArray = fileIdParam.split(",");
System.out.println("Compressing files...");
File archiveFile = new File("C://Users//Administrator//Desktop//archive.zip");

ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(archiveFile));
BufferedOutputStream bufferedStream = new BufferedOutputStream(zipStream);

Map<String, String> responseMap = new HashMap<String, String>();

for (String id : fileIdArray) {
    RemoteFileEntity fileEntity = fileService.findById(Integer.parseInt(id));
    
    if ("0".equals(deviceType)) {
        responseMap.put("download_id", fileEntity.getRemoteId());
        responseMap.put("download_name", fileEntity.getFileName());
        JSONObject jsonResponse = JSONObject.fromObject(responseMap);
        response.getWriter().print(jsonResponse.toString());
    } else {
        packageFile(zipStream, bufferedStream, fileEntity, fileEntity.getFileName());
    }
}

responseMap.put("download_id", "");
JSONObject finalJson = JSONObject.fromObject(responseMap);
response.getWriter().print(finalJson.toString());

bufferedStream.close();
zipStream.close();
System.out.println("Compression completed");

File Packaging Function

private void packageFile(ZipOutputStream zipOut, BufferedOutputStream bufferOut, 
                         RemoteFileEntity fileEntity, String entryName) throws Exception {
    
    if (fileEntity.isDirectory()) {
        String queryParams = "userId:" + fileEntity.getUserId() + ",parentFileId:" + fileEntity.getId();
        List<FileStructure> childFiles = fileStructureService.getAllChildren(queryParams);
        
        if (childFiles.isEmpty()) {
            System.out.println(entryName + "/");
            zipOut.putNextEntry(new ZipEntry(entryName + "/"));
        } else {
            for (int index = 0; index < childFiles.size(); index++) {
                RemoteFileEntity subFile = fileService.findById(childFiles.get(index).getFileId());
                String newEntryName = entryName + "/" + childFiles.get(index).getFileName();
                packageFile(zipOut, bufferOut, subFile, newEntryName);
            }
        }
    } else {
        URL remoteUrl = new URL("http://***.***.***.**:****/" + fileEntity.getRemoteId());
        HttpURLConnection httpConnection = (HttpURLConnection) remoteUrl.openConnection();
        
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.setUseCaches(false);
        httpConnection.setRequestMethod("GET");
        
        httpConnection.setRequestProperty("Content-Type", "application/octet-stream");
        httpConnection.setRequestProperty("Connection", "Keep-Alive");
        httpConnection.setRequestProperty("Charset", "UTF-8");
        
        byte[] fileContent = streamToByteArray(httpConnection.getInputStream());
        
        zipOut.putNextEntry(new ZipEntry(entryName));
        zipOut.write(fileContent);
        zipOut.closeEntry();
    }
}

Tags: file-download remote-files zip-compression java-io http-client

Posted on Sun, 10 May 2026 05:18:47 +0000 by dave_biscuits