Java 对远程文件的操作

首先添加jar

              <dependency>
		    <groupId>jcifs</groupId>
		    <artifactId>jcifs</artifactId>
		    <version>1.3.17</version>
	   </dependency>
            <dependency>
		    <groupId>com.jcraft</groupId>
		    <artifactId>jsch</artifactId>
		    <version>0.1.54</version>
		</dependency>
		       

第一个肯定是要的,第二个最好也配置下。
下面来看代码,和一些方法示例

conStr = "smb://"+account+":"+password+"@"+remoteHostIp+"/"+shareDocName+"/"+remoteFileName;  

	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();  
    } 
    
//    @Async
    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;
    }

上面最重要的就是要把路径那些设置对,其它的都很简单,根据包的方法操作就行。
这边的远程文件是放在window系统中的,且是设置好的。我们通过smb://account:password @ 这样来操作。

原文地址:https://www.cnblogs.com/ylzhang/p/8393209.html