」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在Java中正確透過套接字傳輸檔案?

如何在Java中正確透過套接字傳輸檔案?

發佈於2024-11-17
瀏覽:720

How to Correctly Transfer Files Over Sockets in Java?

Java 透過套接字傳輸檔案:傳送和接收位元組數組

Java 透過套接字傳輸檔案:傳送和接收位元組數組

在Java 中,透過套接字傳輸檔案涉及將檔案轉換為位元組數組,透過套接字發送它們,然後在接收端將位元組轉換回檔案。本文解決了 Java 開發人員在實作此文件傳輸功能時遇到的問題。

伺服器端問題

byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
    fos.write(buffer, 0, bytesRead);
}

byte[] buffer = new byte[1024]; int 位元組讀取 = 0; while ((bytesRead = in.read(buffer)) != -1) { fos.write(緩衝區, 0, bytesRead); }

客戶端問題

FileInputStream is = new FileInputStream(file);
byte[] bytes = new byte[(int) length];
is.read(bytes);
out.write(bytes);

FileInputStream is = new FileInputStream(file); byte[] 位元組 = 新位元組[(int) 長度]; is.read(字節); out.write(bytes);

改進的程式碼

經過上述修正,伺服器與客戶端的完整程式碼如下:

伺服器:
...
byte[] buffer = new byte[1024];
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

FileOutputStream fos = new FileOutputStream("C:\\test2.xml");
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
    fos.write(buffer, 0, bytesRead);
}
fos.close();
...

... 位元組[]緩衝區=新位元組[1024]; DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); FileOutputStream fos = new FileOutputStream("C:\\test2.xml"); int 位元組讀取 = 0; while ((bytesRead = in.read(buffer)) != -1) { fos.write(緩衝區, 0, bytesRead); } fos.close(); ……

客戶:
...
byte[] buffer = new byte[1024];
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

FileOutputStream fos = new FileOutputStream("C:\\test2.xml");
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
    fos.write(buffer, 0, bytesRead);
}
fos.close();
...

... 套接字socket = new Socket(主機, 4444); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); 檔案 file = new File("C:\\test.xml"); FileInputStream = new FileInputStream(檔案); 長長度 = file.length(); 如果(長度> Integer.MAX_VALUE){ System.out.println("檔案太大。"); } byte[] 位元組 = 新位元組[(int) 長度]; is.read(字節); 輸出.write(字節); ...How to Correctly Transfer Files Over Sockets in Java?

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3