2009-10-19 47 views
5

我需要從Windows上運行的Java腳本讀取一堆二進制文件。如何使用提供的用戶名和密碼來讀取Java文件

但是,文件所在的文件夾的權限有限。我(即我的Windows用戶名)有權讀取它們,但Java運行的用戶(這是Web應用程序的一部分)不具有這些權限。如果我在運行時將自己的用戶名和Windows網絡密碼傳遞給Java,是否有一種方法可以使用我自己的權限而不是Web用戶的權限讀取這些文件?

(請注意,這不是發生在網上,這是一個Web應用程序的上下文中運行的一次性導入腳本)。

回答

4

您可以創建一個網絡共享,然後通過jCIFS

import java.io.IOException; 
import java.net.MalformedURLException; 
import java.net.UnknownHostException; 

import jcifs.smb.SmbException; 
import jcifs.smb.SmbFileInputStream; 

public class Example 
{ 
    public static void main(String[] args) 
    { 
     SmbFileInputStream fis = null; 
     try 
     { 
      fis = new SmbFileInputStream("smb://DOMAIN;USERNAME:[email protected]/SHARE/filename.txt"); 
      // handle as you would a normal input stream... this example prints the contents of the file 
      int length; 
      byte[] buffer = new byte[1024]; 
      while ((length = fis.read(buffer)) != -1) 
      { 
       for (int x = 0; x < length; x++) 
       { 
        System.out.print((char) buffer[x]); 
       } 
      } 
     } 
     catch (MalformedURLException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (UnknownHostException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (SmbException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
     finally 
     { 
      if (fis != null) 
      { 
       try 
       { 
        fis.close(); 
       } 
       catch (Exception ignore) 
       { 
       } 
      } 
     } 
    } 
} 
連接
0

如果文件在網絡共享,你可以使用net工具。用

runtime.exec("net use ...") 

打開和關閉該份額。我想這應該工作

相關問題