萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 電腦基礎知識 >  >> 電腦入門

Java 操作 Windows 共享資料夾完整指南:基於 JCIFS 庫的 SMB 客戶端實作

核心概念

SMB 協定簡介

SMB(Server Message Block,伺服器訊息區塊) 是一種客戶端/伺服器檔案共享協定,最初由 IBM 於 1980 年代末開發,用於規範共享網路資源(目錄、檔案、印表機、序列埠)的結構。SMB 採請求/回應模式,與 FTP 不同的是,SMB 客戶端需與伺服器建立長期連線,連線建立後即可如同存取本地資源般存取遠端檔案。

自 Windows 2000 起,微軟將 SMB 移植至 TCP/IP 協定族,透過 DNS 進行名稱解析,使得 SMB 資源共享可直接在標準網路環境下運作。

JCIFS 庫

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 URL 格式:smb://[username:password@]server/share/path,若需驗證請在 URL 中包含帳號密碼。
  • 緩衝區大小:範例使用 1KB,實際應用可視網路與檔案大小調整(如 8KB~64KB)。
  • 例外處理:生產環境建議針對 SmbException、IOException 分別處理,並加入重試機制。
  • 資源釋放:務必在 finally 區塊關閉串流,避免檔案鎖定或記憶體洩漏。

常見應用場景

  • 企業內部系統自動備份檔案至 NAS 共享資料夾。
  • Web 應用讀取/寫入檔案伺服器上的報表、範本檔。
  • 跨平台(Linux/Java 應用)存取 Windows 檔案伺服器。

掌握 JCIFS 基本操作後,即可在 Java 專案中靈活整合 Windows 檔案共享功能。

copyright © 萬盛學電腦網 all rights reserved