在我的客户端服务器应用程序中,我使用了命令(GET filename
)将文件下载到客户端。我已经使用read()
方法中的构建来读取文件。我的老师说,实施此read
方法不是一个很好的做法。原因是它不能说明该文件是如何从服务器读取的,或者以某种方式无法下载动态(大)文件大小。但是目前我发现它运行良好。由于我仍处于Java的中级水平,因此我需要学习完成这项工作的最佳方法。如何改进编码?那就是我想改善客户端中的while looping
部分。
我粘贴了相关代码:
客户端:
............
............
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 OKrn"
+ "Size " + fileSize + "KB" + "rn"
+ "rn"
+ "File " + filename + " Download was successfullyrn");
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 400rn"
+ "File " + filename + " not foundrn"
+ "rn");
outputToClient.flush();
}
}
outputToClient.flush();
}
.................
.................
您需要通过阅读直到获得空白,如果您尚未完成,则需要消耗其余的HTTP响应标头。
除此之外,您的代码对我来说看起来不错,除了我使用的缓冲区比127大得多,至少8192,可能是其中的一个。
问你的老师他在说什么。