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(字節); ...
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3