Java: 使用jCIFS存取遠端網路磁碟機的檔案

使用遠端的NAS當做網路磁碟機時,會遇到一個狀況:若AP Server以服務的形式啟動時,會抓不到網路磁碟機。有兩個方法可以解決程式存取網路磁碟機的狀況。

方法1. 設定服務的登入帳戶

AP Server服務的登入帳戶不要使用預設的「本機系統帳戶」,以登入NAS的帳號、密碼來建立本機帳戶,再將服務的登入帳戶變更為此新建帳戶,則程式裡就能以UNC的方式存取網路磁碟機(如 \\192.168.0.1\share\doc)。

方法2. 使用jCIFS套件

jCIFS是CIFS(Common Internet File System)的Java實作,以smb://通訊協定來溝通Windows與Linux(Samba)。使用紀要如下:

1.登入NAS,先建立NTLM認證:

NtlmPasswordAuthentication auth = 
    new NtlmPasswordAuthentication(null, 帳號, 密碼);

2.列出遠端的檔案清單

String remoteURL = "smb://192.168.0.1/share/doc";
SmbFile dir = new SmbFile(remoteURL, auth);
for (SmbFile f : dir.listFiles()) {
  System.out.println("File name: " + f.getName());
}

3. 將遠端檔案存入本地磁碟

SmbFile smbFile = new SmbFile("smb://192.168.0.1/share/doc/test1.doc", auth);
  SmbFileInputStream inputSmbFile = null;
  FileOutputStream outputFile = null;
  try {
    String filename = smbFile.getName();
    inputSmbFile = new SmbFileInputStream(smbFile);
    outputFile = new FileOutputStream(new File(destDir + filename));
    while ((len = inputSmbFile.read(buf)) > 0) {
      outputFile.write(buf, 0, len);
    }
  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    if (inputSmbFile != null) inputSmbFile.close();
    if (outputFile != null) outputFile.close();
  }

4. 將本地檔案存入遠端

SmbFileOutputStream outputSmbFile = null;
    FileInputStream inputFile = null;
    try {
      File file = new File(sSrcFile);
      String filename = file.getName();
      SmbFile smbFile = new SmbFile(sRemoteURL_ + filename, auth);
      outputSmbFile = new SmbFileOutputStream(smbFile);
      inputFile = new FileInputStream(file);
      while ((len = inputFile.read(buf)) > 0) {
        outputSmbFile.write(buf, 0, len);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (outputSmbFile != null) outputSmbFile.close();
      if (inputFile != null) inputFile.close();
    }

##

您可能也會有興趣的類似文章

簡睿

服務於軟體業的資訊老兵。興趣廣泛,學習力佳,樂於分享所知所學。

您可能也會喜歡…

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *