富客戶端架構下,RMI 與 Socket 為主要通信選項。RMI 優勢在於調用透明、序列化內建,劣勢是異語言互操作受限。本文採用「文件→字節數組→RMI 參數→字節數組→文件」折中方案。
| 組件 | 職責 |
| FileDataService | 遠程接口,定義 upload(String filename, byte[] file) |
| FileDataService_imp | 服務端實現,字節數組寫入磁盤 |
| FileServer | 註冊 RMI Registry,綁定服務 |
| FileClient | 讀取文件為字節數組,調用遠程上傳 |
核心代碼解析
客戶端文件轉字節數組
private byte[] fileToByte(String filename) {
File file = new File(filename);
byte[] b = new byte[(int) file.length()];
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(file))) {
is.read(b); // 注意:大文件需分塊讀取,單次 read 不保證讀滿
} catch (IOException e) { e.printStackTrace(); }
return b;
}
服務端字節數組存文件
@Override
public void upload(String filename, byte[] fileContent) throws RemoteException {
File file = new File(filename);
if (!file.exists()) file.createNewFile();
try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
os.write(fileContent);
} catch (IOException e) { e.printStackTrace(); }
}
服務啟動與註冊
LocateRegistry.createRegistry(9001);
Naming.rebind("rmi://localhost:9001/FileDataService", new FileDataService_imp());
方案局限與改進
- 內存壓力:大文件全量讀入堆內存易導致 OOM,建議分塊傳輸(如 1MB/塊)
- 完整性校驗:引入 MD5/SHA-256 校驗碼雙向驗證
- 斷點續傳:服務端記錄已接收塊索引,客戶端續傳未完成部分
- 替代方案:Netty/HTTP 分塊上傳、FTP/SFTP、對象存儲預簽名 URL
運行步驟
- 啟動
FileServer,Registry 啟動在 9001 端口
- 運行
FileClient,指定本地文件路徑與目標服務端路徑
- 驗證服務端目標目錄生成文件,大小一致
- 上一篇文章: Java Properties 屬性文件完整讀寫指南與最佳實踐
- 下一篇文章: Java 調用百度 IP 定位 API 獲取地理位置實戰
Copyright ©
程式碼之家 All Rights Reserved