Java操作网络共享资源

一、背景介绍
1、有些需求中需要定时将信息写入到对方开发的共享文件夹中,这时就需要进行远程操作。
2、这个使用需要对方共享文件夹开放对应的读写权限。
3、这次用的是CIFS,通用Internet文件系统, 在windows主机之间进行网络文件共享是通过使用微软公司自己的CIFS服务实现的。 
二、实现逻辑
    1、共享的文件夹常见的有两种:访问时需要用户名+密码和访问时不需要文件名和密码,这都有文件夹设置的权限决定。
    2、smb://用户名:密码@IP/文件路径 VS smb://IP/文件路径
    3、读取操作是将共享文件以流的方式返回了,若要提取则可以写入到文件流中。
    4、写入操作也是将操作编程对流的操作,通过NtlmPasswordAuthentication("",username(没有即为null),password(没有即为null)对象将远程目录当成本地来操作。
    5、将流对象自己拷贝到远程文件中。
三、具体操作。
1、对远程文件进行读取操作。
    SmbFile smbFile = new SmbFile("smb://administrator: 1234@192.168.3.56/share/a.txt");
     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();
2、对远程文件写入操作。
  OutputStream fileOutputStream = null;
    FileInputStream fileInputStream = null;
    NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
            "username", "password");
    try {
        SmbFile remoteFile = new SmbFile(remoteName, auth);
        SmbFile remoteDir = new SmbFile(remoteFile.getParent(), auth);
        // create remote folder if not exist
        if (!remoteDir.exists())
            remoteDir.mkdirs();
        // create remote file
        if (!remoteFile.exists())
            remoteFile.createNewFile();
        remoteFile.setReadWrite();
        byte[] buf;
        int len;
        try {
            fileInputStream = new FileInputStream(localName);
            fileOutputStream = remoteFile.getOutputStream();

            buf = new byte[16 * 1024 * 1024];
            while ((len = fileInputStream.read(buf)) > 0) {
                fileOutputStream.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fileInputStream.close();
            fileOutputStream.close();

        }
3、需要的maven配置。
<dependency>
    <groupId>jcifs</groupId>
    <artifactId>jcifs</artifactId>
    <version>1.3.17</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值