2012年3月29日 星期四

Servlet unable to access map network drive on Windows platform

Use JCIFS to solve the problem http://jcifs.samba.org/
JCIFS API Doc: http://www.jarvana.com/jarvana/view/org/samba/jcifs/jcifs/1.2.19/jcifs-1.2.19-javadoc.jar!/index.html

1. Add jcifs-1.3.17.jar to lib.
2. configure connection path with login credential:
String path = "smb://administrator:password@{server-ip}/sharedFolderName/subfolder/a.txt";

3.
//check file existence using SmbFile class
SmbFile sFile = new SmbFile(path);

System.out.println(path +" exist?"+sFile.exists());
System.out.println("can read?"+sFile.canRead());

//read from SmbFile
InputStream sFileIn = sFile.getInputStream();
int length = 0;
    int BUFSIZE = 1024;
    byte[] bbuf = new byte[BUFSIZE];
    while ((sFileIn != null) && ((length = sFileIn.read(bbuf)) != -1))
    System.out.write(bbuf, 0, length);

//write to SmbFile
public void writeFile(String path) throws Exception {
    path = "smb://administrator:password@server-ip/iViewerFiles/study_unit/test2.txt";
    SmbFile sFile = new SmbFile(path);
    SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
    sfos.write("Muneeb Ahmad".getBytes());
    }
 
//copy SmbFile to local file
public void copyFile(String path) throws Exception{
     path = "smb://administrator:password@server-ip/iViewerFiles/study_unit/test2.txt";
     SmbFile sFile = new SmbFile(path);
   
    File destFile = new File("C:/temp/btest.txt");
   
    InputStream sFileIn = sFile.getInputStream();
    FileOutputStream fos = new FileOutputStream(destFile);
    int length = 0;
    int BUFSIZE = 1024;
    byte[] bbuf = new byte[BUFSIZE];
    while ((sFileIn != null) && ((length = sFileIn.read(bbuf)) != -1)){
    //System.out.write(bbuf, 0, length);
    fos.write(bbuf,0,length);
    }
    sFileIn.close();
fos.close();
   
    }
 
 


沒有留言:

張貼留言