gpt4 book ai didi

java - 从服务器(Java)读取/下载文件的准确方法是什么?

转载 作者:行者123 更新时间:2023-12-01 11:33:44 25 4
gpt4 key购买 nike

在我的客户端-服务器应用程序中,我使用命令(GET filename)将文件下载到客户端。我使用了 build in read() 方法来读取文件。我的老师说实现这个 read 方法并不是一个很好的做法。原因是它不知道文件是如何从服务器读取的,或者它以某种方式无法下载动态(大)文件大小。但目前我发现它运行良好。由于我的java仍处于中级水平,我需要学习完成这项工作的最佳方法。编码方面如何改进?那就是我想改进ClientSide中的while循环部分。

我已经粘贴了相关代码:

客户端:

                         ............
............
if (request.startsWith("GET")) {
File file = new File(request.substring(4));
is = socket.getInputStream();
fos = new FileOutputStream(file);

byte[] buffer = new byte[socket.getReceiveBufferSize()];
int bytesReceived = 0;

while ((bytesReceived = is.read(buffer)) >=0) {
//while ((bytesReceived = is.read(buffer))>=buffer) {
fos.write(buffer, 0, bytesReceived);
}
request = "";
fos.close();
is.close();
}
.................
.................

服务器端:

                          .................
.................
else if (request.startsWith("GET")) {
System.out.println("");
String filename = request.substring(4);
File file = new File(System.getProperty("user.dir"));
File[] files = file.listFiles();

if (fileExists(files, filename)) {
file = new File(filename);
int fileSize = (int) file.length();
outputToClient.print("Status OK\r\n"
+ "Size " + fileSize + "KB" + "\r\n"
+ "\r\n"
+ "File " + filename + " Download was successfully\r\n");
outputToClient.flush();
// reading files
fis = new FileInputStream(file);
os = socket.getOutputStream();
byte[] buffer = new byte[2^7-1];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer))!= -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} else {
outputToClient.print("Status 400\r\n"
+ "File " + filename + " not found\r\n"
+ "\r\n");
outputToClient.flush();
}
}
outputToClient.flush();
}
.................
.................

最佳答案

如果您还没有这样做,您需要阅读其余的 HTTP 响应 header ,直到出现一个空行。

除此之外,你的代码对我来说看起来不错,只是我会使用比 127 大得多的缓冲区,至少 8192,可能是它的倍数。

问问你的老师他在说什么(到底)。

关于java - 从服务器(Java)读取/下载文件的准确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30212130/

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