2012-05-15 74 views
7

我想在共享網絡驅動器上放置.txt文件。路徑是網絡驅動器上的地圖,需要憑據(登錄名和密碼)。我可以使用FileOutputStream傳遞這些參數嗎?使用憑證將I/O文件寫入共享網絡驅動器

 FileOutputStream fos; 
     DataOutputStream dos; 

     try { 
      File file= new File(path + "/" + fileName + ".txt"); 
      fos = new FileOutputStream(file); 
      dos=new DataOutputStream(fos); 
      dos.writeChars(stringContent); 
      dos.close(); 
      fos.close(); 
     } 
     catch(IOException eio){ 
     } 

謝謝

回答

12

號使用Java CIFS Client library。你可以通過java連接遠程windows機器。例如 -

String user = "user:password"; 
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user); 
String path = "smb://my_machine_name/D/MyDev/test.txt"; 
SmbFile sFile = new SmbFile(path, auth); 
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile); 
sfos.write("Test".getBytes()); 
sfos.close(); 

感謝

+1

不要有任何這方面的經驗:現在,我使用自定義庫,我需要把它列入.jar文件什麼的? jar文件還能如何處理這些類? – Hazaart

+0

從[http://jcifs.samba.org/src/](http://jcifs.samba.org/src/)下載jcifs-1.1.11.jar jar並將此jar添加到您的構建路徑。 –

+2

如果你有域名,那麼你必須使用域名;用戶:密碼 –

0

此代碼爲我工作:

public void downloadFromNetworkDrive3() throws MalformedURLException, SmbException, IOException { 
     String user = "domain;username:password";//domain name which you connect 
     NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user); 
     String path = "smb://198.168.20.27/D$/MICROS/opera/export/OPERA/dinaamum/audit/Thumbs.db"; 

     SmbFile sFile = new SmbFile(path, auth); 
     SmbFileOutputStream sfos; 
     SmbFileInputStream sfis; 
     try { 
//  sfos = new SmbFileOutputStream(sFile); 
      sfis = new SmbFileInputStream(sFile); 

//  sfos.write("hihowareyou".getBytes()); 
      File tempFile = null; 
      String filePath = null; 
      filePath = "c://usr/local/cache/leelafiles"; 
      tempFile = new File(filePath); 
      if (tempFile.exists()) { 
      } else { 
       tempFile.mkdirs(); 
      } 
      tempFile = new File(filePath); 
//  File[] allFilesAndDirs = tempFile.listFiles(); 
      FileOutputStream writer = new FileOutputStream(tempFile + File.separator + "Thumbs.db"); 
      byte[] b = new byte[8192]; 
      int n; 
      while ((n = sfis.read(b)) > 0) { 
       System.out.write(b, 0, n); 
       writer.write(b, 0, n); 
      } 
      sfis.close(); 
      writer.close(); 

     } catch (UnknownHostException ex) { 
      Logger.getLogger(ReportSchedulerJob.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 
+1

請不要只轉儲代碼,在上下文中解釋OP ..您還包含第三方jar [CIFS客戶端庫](https://jcifs.samba.org/) –

+0

對不起!是的,我忘了寫上下文,但是這個代碼用於從網絡驅動器使用用戶名和密碼讀取任何文件,它需要第三方jar CIFS客戶端庫 –

相關問題