[英]What is the accurate way to read/download a file from the server (in Java)?
在我的客戶端服務器應用程序中,我使用了命令( GET filename
)將文件下載到客戶端。 我已使用read()
方法中的內置方法來讀取文件。 我的老師說,實施這種read
方法不是一個很好的做法。 原因是它無法說明從服務器讀取文件的確切方式,還是無法下載動態(大)文件大小。 但是目前,我看到它運行良好。 由於我仍處於Java的中級水平,因此我需要學習完成這項工作的最佳方法。 如何在編碼中進行改進? 那就是我想改善ClientSide中的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 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響應標頭,方法是讀取直到獲得空白行(如果尚未完成)。
除此之外,您的代碼對我來說看起來還不錯,除了我將使用比127大得多的緩沖區(至少8192,可能是該倍數)。
問你的老師在說什么(到底)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.