SMB(Server Message Block,伺服器訊息區塊) 是一種客戶端/伺服器檔案共享協定,最初由 IBM 於 1980 年代末開發,用於規範共享網路資源(目錄、檔案、印表機、序列埠)的結構。SMB 採請求/回應模式,與 FTP 不同的是,SMB 客戶端需與伺服器建立長期連線,連線建立後即可如同存取本地資源般存取遠端檔案。
自 Windows 2000 起,微軟將 SMB 移植至 TCP/IP 協定族,透過 DNS 進行名稱解析,使得 SMB 資源共享可直接在標準網路環境下運作。
JCIFS 是純 Java 實作的 SMB 客戶端庫,支援操作 Windows 共享檔案、取得網域使用者資訊、實現單一登入(SSO)等功能。最新版本 1.3.12,官網:jcifs.samba.org。
package uploadSMB;
import java.io.*;
import jcifs.smb.*;
public class UploadDownloadUtil {
/**
* 從共享目錄下載檔案到本地
* @param remoteUrl 共享檔案完整路徑 (smb://user:pass@host/share/path/file)
* @param localDir 本地儲存目錄
*/
public void smbGet(String remoteUrl, String localDir) {
InputStream in = null;
OutputStream out = null;
try {
SmbFile remoteFile = new SmbFile(remoteUrl);
if (remoteFile == null || !remoteFile.exists()) {
System.out.println("共享檔案不存在");
return;
}
String fileName = remoteFile.getName();
File localFile = new File(localDir + File.separator + fileName);
in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
out = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (out != null) out.close(); } catch (IOException ignored) {}
try { if (in != null) in.close(); } catch (IOException ignored) {}
}
}
/**
* 從本地上傳檔案到共享目錄
* @param remoteUrl 共享目錄路徑 (smb://user:pass@host/share/)
* @param localFile 本地檔案完整路徑
*/
public void smbPut(String remoteUrl, String localFile) {
// 實作邏輯類似 smbGet,使用 SmbFileOutputStream
// 此處省略,請參考 JCIFS 官方文件補全
}
}
smb://[username:password@]server/share/path,若需驗證請在 URL 中包含帳號密碼。SmbException、IOException 分別處理,並加入重試機制。finally 區塊關閉串流,避免檔案鎖定或記憶體洩漏。掌握 JCIFS 基本操作後,即可在 Java 專案中靈活整合 Windows 檔案共享功能。