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类里的方法。

  • 相关阅读:
    第四次作业--个人作业--软件案例分析
    第五次作业--团队项目--需求规格说明书
    Beta版本的贡献率
    软工实践总结
    beta版本冲刺第四天
    beta版本冲刺第三天
    beta版本冲刺第一天
    Beta版本冲刺计划及安排
    团队项目冲刺总结
    项目冲刺第六天
  • 原文地址:https://www.cnblogs.com/ylzhang/p/7562009.html
Copyright © 2011-2022 走看看