gpt4 book ai didi

java - 通过socket继续中断的下载

转载 作者:行者123 更新时间:2023-12-02 05:47:23 26 4
gpt4 key购买 nike

我正在尝试继续从服务器到客户端的中断下载。

发送的服务器代码:

long fileLength = file.length();
String fileName = file.getName();
int bytesRead = 0;
long bytesReadAmount = 0;
byte[] byteArray = new byte[6 * PACKET_SIZE];

OutputStream outputStream = socket.getOutputStream();

try {
BufferedInputStream bufferedIS = new BufferedInputStream(new FileInputStream(file));
while ((bytesRead = bufferedIS.read(byteArray)) > 0) {
outputStream.write(byteArray, (int)existingFileSize, bytesRead);
bytesReadAmount += bytesRead;
System.out.println("File sending " + fileName + " (send" + bytesReadAmount + " byte, remain " +
(fileLength - bytesReadAmount));
}
System.out.println("File transfer end");
} catch (IOException e) {
System.out.println("File transfer error");
e.printStackTrace();
} finally {
dataOS.flush();
socket.close();
}

客户端接收代码

long bytesReadAmount = 0;
int bytesRead = 0;
long size = 0;
byte[] byteArray = new byte[6 * Server.PACKET_SIZE];

try {
File file = new File(DIRECTORY_PATH + fileName);
file.createNewFile();
FileOutputStream fileOS = new FileOutputStream(file);
BufferedOutputStream bufferedOS = new BufferedOutputStream(fileOS);

while ((bytesRead = dataIS.read(byteArray)) != -1) {
bufferedOS.write(byteArray, (int)existingFileSize, bytesRead);
bytesReadAmount += bytesRead;
System.out.println("File receiving " + fileName + " (" + bytesReadAmount + " bytes received)");
}
System.out.println("File " + fileName + " sending OK");
} catch (IOException e) {
System.out.println("Connection interrupted");
e.printStackTrace();
}
}

从头到尾发送大文件效果很好,但中断后继续下载却不行(当我尝试继续中断的文件时,发送不起作用)。另外,当我发送完整文件时,副本的大小与原始文件的某些字节不同。请帮忙解决这个问题

最佳答案

您在 write(byteArray, (int)existingFileSize, bytesRead) 中使用的 offsetbyteArray 中的偏移量,而不是原始偏移量文件。我建议您使用 skip() 跳过要读取或写入的数据,并在重新启动时附加到文件(通过在 FileOutputStream 构造函数中设置附加)

关于java - 通过socket继续中断的下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23929222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com