zoukankan      html  css  js  c++  java
  • 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类里的方法。

  • 相关阅读:
    1048. Find Coins (25)
    return view 详解 MVC
    EF Power Tool 代码生成器 反向生成
    对新数据库使用 Code First
    一个成熟的网站的架构设计应该是这样的
    公司业务的设计思想感悟
    请给奋斗中的男人们一次机会
    大话西游感悟
    充满恶意的单词
    lisp的解释器
  • 原文地址:https://www.cnblogs.com/ylzhang/p/7562009.html
Copyright © 2011-2022 走看看