java遠程文件操作


有時在項目中,會有專門的文件服務器(windows),這個時候我們需要對文件進行操作時,就不能像操作本地文件那樣操作文件服務器的文件。這時候就可以用SmbFile來操作了。
首先添加jar包,maven中添加如下代碼:

<dependency>
     <groupId>jcifs</groupId>
	    <artifactId>jcifs</artifactId>
     <version>1.3.17</version>
</dependency>

一般通過文件服務器操作都需要賬號密碼,這時候需要設置下最基本的設置,

public static final String fileRoot = "smb://remotename:remotepassword@";

public InputStream getFile(String path) throws IOException {
		SmbFile smbFile = new  SmbFile(fileRoot+path); 
		return smbFile.getInputStream();
}

public   static   void  smbGet1(String remoteUrl)  throws  IOException {  
        SmbFile smbFile = new  SmbFile(remoteUrl);  
        int  length = smbFile.getContentLength(); // 得到文件的大小   
        byte  buffer[] =  new   byte [length];  
        SmbFileInputStream in = new  SmbFileInputStream(smbFile);  
        // 建立smb文件輸入流   
        while  ((in.read(buffer)) != - 1 ) {  
  
            System.out.write(buffer);  
            System.out.println(buffer.length);  
        }  
        in.close();  
    } 

 public static List<AttachmentPO> getAttachmentFiles(String remoteDirectory) 
    {
    	List<AttachmentPO> attachmentPOs = new ArrayList<AttachmentPO>();
    	try {
			SmbFile file = new SmbFile(fileRoot + remoteDirectory);
			String[] files = file.list();
			for(String name : files){
				AttachmentPO AttachmentPO = new AttachmentPO();
				AttachmentPO.setName(name);
				AttachmentPO.setFile_path(remoteDirectory + name); 
				AttachmentPO.setRef_type(WikiConsts.ATTACHMENT_TYPE_DOWNLOAD);
				attachmentPOs.add(AttachmentPO);
			}

		} catch (MalformedURLException e) {
			logger.error("get SmbFile by directory return wrong, the remoteDirectory is" + remoteDirectory);
		} catch (SmbException e) {
			logger.error("get SmbFiles under directory return wrong, the remoteDirectory is" + remoteDirectory);
		}
    	return attachmentPOs;
    }

其它的一些操作方法和本地操作文件方法沒什么大的區別,可以自行地研究這個SmbFile類里的方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM