Как возобновить загрузку файла с помощью httpurlconnection в Java после сбоя сети? [закрыто]JAVA

Программисты JAVA общаются здесь
Anonymous
Как возобновить загрузку файла с помощью httpurlconnection в Java после сбоя сети? [закрыто]

Сообщение Anonymous »

Как возобновить загрузку файлов с использованием httpurlconnection в Java после сбоя сети?
Я пытаюсь улучшить свой загрузчик файлов java, чтобы он мог , если подключение будет прерывается (например, из -за неудачи сети). Возобновляясь, отправив заголовок диапазона на сервер. Тем не менее, я не уверен, как правильно реализовать эту логику: < /p>

Проверьте размер частично загруженного файла < /li>
Установите правильный диапазон < /code> в http -запросе < /li>
Доклады в существующий файл без перевозки < /li>
< /br /> < /br />
< /br /> < /br /> < /br />
< /br /> < /li> < /li> < /br /> (Базовый) Код, который я использую, который загружает файл с самого начала каждый раз :
public static void downloadFileWithResume(String fileURL, String destination) throws IOException {
File file = new File(destination);
long existingFileSize = file.exists() ? file.length() : 0;

URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

if (existingFileSize > 0) {
httpConn.setRequestProperty("Range", "bytes=" + existingFileSize + "-");
System.out.println("Resuming download from byte " + existingFileSize);
}

int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_PARTIAL || responseCode == HttpURLConnection.HTTP_OK) {
try (InputStream inputStream = httpConn.getInputStream();
RandomAccessFile outputFile = new RandomAccessFile(destination, "rw")) {

outputFile.seek(existingFileSize);

byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputFile.write(buffer, 0, bytesRead);
}
}
} else {
throw new IOException("Server replied with HTTP code: " + responseCode);
}

httpConn.disconnect();
}
}

package com.example.archivibility.afardi.archivibilty;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.Collections;
import java.io.IOException;

public class DataTransfer {
// خصوصیات کلاس
private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
private List dataList = Collections.synchronizedList(new ArrayList());
private ArchivabilityDataManager archivabilityDataManager;

// روش برای برنامه‌ریزی فعالیت insertData هر 10 ثانیه
public void insertDataService() {
service.scheduleWithFixedDelay(this::insertData, 0, 10, TimeUnit.SECONDS);
}

// روش برای ذخیره داده‌ها در فایل
public void insertData() {
// اضافه کردن افراد به لیست
dataList.add(new Person("amir"));
dataList.add(new Person("leila"));
dataList.add(new Person("hossein"));
dataList.add(new Person("bita"));
dataList.add(new Person("milad"));
dataList.add(new Person("reza"));
dataList.add(new Person("amir"));

// حلقه برای ذخیره هر شخص در فایل
for (Person person : dataList) {
try {
archivabilityDataManager = new ArchivabilityDataManager("src/main/java/com/example/archivibility/afardi/archivibilty/", 11);
archivabilityDataManager.saveData("data", person.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}

// روش برای خاموش کردن خدمات
public void shutDown() {
service.shutdown();
}
}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
public static void main(String[] args) {
String inputFile = "input.txt";
String inputCheckpointFile = "checkPoint.txt";

try {
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String line;
BufferedReader readerCheck = new BufferedReader(new FileReader(inputCheckpointFile));

if (readerCheck.ready()) {
String lastLine = readerCheck.readLine();
if (lastLine != null) {
String[] input = lastLine.split(" ");
while ((line = reader.readLine()) != null) {
if (!lastLine.contains("CRASH") && Integer.parseInt(line.split(" ")[1]) < Integer.parseInt(input[1])) {
continue;
}
processLine(line);
if (lastLine.contains("CRASH")) {
saveLastLineCheckpoint(reader);
throw new RuntimeException("Simulated crash!");
}
}
}
} else {
while ((line = reader.readLine()) != null) {
processLine(line);
if (line.contains("CRASH")) {
saveLastLineCheckpoint(reader);
throw new RuntimeException("Simulated crash!");
}
}
}

System.out.println("Processing completed.");
} catch (IOException e) {
e.printStackTrace();
}
}

private static void processLine(String line) {
System.out.println("Processing: " + line);
// فرض کنید اینجا پردازش اصلی انجام می‌شود
}

private static void saveLastLineCheckpoint(BufferedReader reader) {
try (FileWriter writer = new FileWriter("checkPoint.txt")) {
writer.write(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}

@RestController
@RequestMapping("/numbers")
public class NumberController {

private final RestTemplate restTemplate;

@Autowired
public NumberController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

@PostMapping("/sum")
public ResponseEntity getSum(@RequestBody List numbers) {
String url = "http://localhost:8080/sum/calculate";
ResponseEntity response = restTemplate.postForEntity(url, numbers, Integer.class);
return ResponseEntity.ok(response.getBody());
}
}


Подробнее здесь: https://stackoverflow.com/questions/796 ... twork-fail

Вернуться в «JAVA»