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:[email protected]/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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章