码迷,mamicode.com
首页 > 编程语言 > 详细

java远程文件操作

时间:2018-10-16 17:44:41      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:tle   输入   file_path   put   window   1.3   return   while   setname   

有时在项目中,会有专门的文件服务器(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类里的方法。

java远程文件操作

标签:tle   输入   file_path   put   window   1.3   return   while   setname   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!