Java通过JCIFS访问操作Windows(smb)共享目录方法代码
时间:2022-10-01
1、引入JCIFS的方法
1) 通过Maven引入(pom.xml)
<dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.2.19</version>
</dependency>
2) JCIFS官网下载Jar
下载地址:https://www.jcifs.org/src/
2、连接共享目录和验证帐户密码
//import jcifs.smb.NtlmPasswordAuthentication; //import jcifs.smb.SmbFile; //import jcifs.smb.SmbFileOutputStream; //权限, 刚开始没有验证权限报过错误 NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("smb://192.168.11.31","UserName", "Password"); SmbFile file = new SmbFile("smb://192.168.0.1/ShareName/FolderName/", auth); if (!file.exists()){ System.out.println("exists is true"); }
3、列出显示出共享目录中的SmbFile
//import jcifs.smb.NtlmPasswordAuthentication; //import jcifs.smb.SmbFile; //import jcifs.smb.SmbFileOutputStream; NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("smb://192.168.11.31","UserName", "Password"); SmbFile smbToFile = new SmbFile("smb://192.168.0.1/ShareName/FolderName/", auth); if(smbToFile.isDirectory()){ for(SmbFile smbfile: smbToFile.listFiles("*")){ System.out.println("getName: " +smbToFile.getName()); } } else{ System.out.println("SupplierDrawingList: Directory Name: Not a Directory: "); }
4、上传文件到共享目录
/** * 向共享目录上传文件 * @param remoteUrl * @param localFilePath */ public void uploadFile(String remoteUrl, String localFilePath) { try { File localFile = new File(localFilePath); String fileName = localFile.getName(); //权限, 刚开始没有验证权限报过错误 NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("smb://192.168.11.31","UserName", "Password"); SmbFile file = new SmbFile(remoteUrl, auth); //当成file用 if (!file.exists()){ file.mkdirs(); } //下面一行本来打算想新建File在指定目录下并且指定文件名,后面发现第一个参数与File同方法参数意义不同 SmbFile remoteFile = new SmbFile( file.getURL() + "/" + fileName); IOUtils.copy(new FileInputStream(localFile), new SmbFileOutputStream(remoteFile)); } catch (Exception e) { e.printStackTrace(); } }
5、下载共享目录文件到本地
InputStream in = null ; ByteArrayOutputStream out = null ; try { //Create a remote file object //String remotePhotoUrl = "smb://share:admin@192.168.135.11/sharedFolder/test.jpg"; NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("smb://192.168.11.31","UserName", "Password"); SmbFile remoteFile = new SmbFile(remoteUrl, auth); remoteFile.connect(); //尝试连接 in = new BufferedInputStream(new SmbFileInputStream(remoteFile)); out = new ByteArrayOutputStream((int)remoteFile.length()); //读取文件内容 byte[] buffer = new byte[4096]; int len = 0; //Read length while ((len = in.read(buffer, 0, buffer.length)) != - 1) { out.write(buffer, 0, len); } out.flush(); //方法刷新此输出流并强制将所有缓冲的输出字节被写出 return out.toByteArray(); } catch (Exception e) { String msg = "Download a remote file error: " + e.getLocalizedMessage(); System.out.println(msg); } finally { try { if(out != null) { out.close(); } if(in != null) { in.close(); } } catch (Exception e) {} }
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。