java通过SmbFile操作远程共享盘内文件(非网络挂在盘,类似\\192.168.1.1这种共享盘)

本文介绍如何使用jcifs库在Java中操作SMB共享文件,包括列出共享文件夹中的所有文件和复制文件的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先导入jcifs-1.3.15.jar包或导入以下依赖

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

话不多说,然后就是敲demo了

/**

*列出共享文件夹中所有文件

*/

  public String[] listFile(String url) {

        SmbFile remoteFile = new SmbFile(url);
          if(remoteFile.exists()) {
                        String[] files = remoteFile.list();
                        remoteFile.connect();
                        String[] files = remoteFile.list();

                       return  files;
                }

               return null;

   }

     /**
     * 复制图片
     * @param oldpath文件共享路径
     * @param newpath本地路径
     * @param filename文件名
     */
    public void copyFile(String oldpath,String newpath,String filename) {
        SmbFile remoteFile = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            remoteFile = new SmbFile(oldpath+filename);
            remoteFile.connect();
            System.out.println(filename+"复制的文件是否存在:"+remoteFile.exists());
            if(remoteFile==null) {
                return ;
            }    
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            out = new BufferedOutputStream(new FileOutputStream(newpath+File.separator+filename));
            byte[] buffer = new byte[1024];  
            while (in.read(buffer) != -1)  
            {  
                out.write(buffer);  
                buffer = new byte[1024];  
            }  
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(out!=null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }                
            }
            if(in!=null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
            }
        }
        
    }                 

▄█▀█●老铁,站住!别跑,我又不收你钱,如果我的demo能够帮助到你,请给我一个赞吧!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值