JAVA实现上传下载共享文件
2015-09-11 14:34
417 查看
1、上传下载共享文件需要用到jcifs,先下载相关JAR包(开源项目的源码,demo,文挡、API应有尽有)
https://jcifs.samba.org/src/
2、创建共享目录,确定访问用户及密码(用户需要写入权限)
3、用户凭证,用户凭证还可以通过远程路径传递(smb://用户名:密码@192.168.0.11/test )
4、上传
5、下载
https://jcifs.samba.org/src/
2、创建共享目录,确定访问用户及密码(用户需要写入权限)
String url_share_key = "192.16.20.15"; //共享IP String url_share_user = "administrator"; //共享用户 需要有写入权限 String url_share_pwd = "123456"; //密码 String dir_share_key = "192.16.20.15/test/"; //共享根路径
3、用户凭证,用户凭证还可以通过远程路径传递(smb://用户名:密码@192.168.0.11/test )
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(url_share_key, url_share_user, url_share_pwd);
4、上传
/** * 从本地上传文件到共享目录 * @param remoteUrl 远程路径 * @param localFilePath 本地路径 * @param auth 用户凭证 */ public static void smbPut(String remoteUrl, String localFilePath,NtlmPasswordAuthentication auth) { InputStream in = null; OutputStream out = null; try { // 需要上传的文件 取出文件名称 File localFile = new File(localFilePath); String fileName = localFile.getName(); // 共享目录 不存在则创建 SmbFile remoteFileDir = new SmbFile(remoteUrl, auth); if (!remoteFileDir.isDirectory()) { remoteFileDir.mkdirs(); } // 上传 SmbFile remoteFile = new SmbFile(remoteUrl + File.separator + fileName, auth); in = new BufferedInputStream(new FileInputStream(localFile)); out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile)); // 缓冲数组 byte[] b = new byte[1024 * 5]; int len; while ((len = in.read(b)) != -1) { out.write(b, 0, len); } // 刷新此缓冲的输出流 out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } }
5、下载
/** * 从共享目录拷贝文件到本地 * @param remoteUrl 远程路径 * @param localDir 本地路经 * @param auth */ public static void smbGet(String remoteUrl, String localDir,NtlmPasswordAuthentication auth) { InputStream in = null; OutputStream out = null; try { //远程文件 SmbFile remoteFile = new SmbFile(remoteUrl,auth); if (remoteFile == null) { System.out.println("共享文件不存在"); return; } //创建本地文件并写入 String fileName = remoteFile.getName(); File localFile = new File(localDir + File.separator + fileName); in = new BufferedInputStream(new SmbFileInputStream(remoteFile)); out = new BufferedOutputStream(new FileOutputStream(localFile)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) { out.write(buffer); buffer = new byte[1024]; } } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } }
相关文章推荐
- JDK 源码笔记 -- List篇
- 【java】抽象类和接口的区别
- java中的分代垃圾回收策略
- 【学习笔记】系列一:Java导出、运行jar包的方法
- 导入myeclipse项目出现的问题及解决方案
- java常规八种基本类型
- Java 笔记之 ---集合总结
- Java 元注解
- Java单例模式
- java.util.concurrent包中线程安全的集合简介
- Annotation(四)——Struts2注解开发
- java深度复制和浅度复制
- 学习日志---最短路径算法
- Annotation(三)——Spring注解开发
- Java Socket 编程之Socket与ServerSocket的区别
- java基础数据类型包装类的作用
- eclipse使用
- Spring Collections(List,Set,Map,Properties)
- java des 加密/解密
- Spring学习(十三)aop技术理解与使用