您的位置:首页 > 编程语言 > Java开发

Java 通过SMB服务远程下载文件及zip包中的文件

2011-10-08 22:12 501 查看
jcifs是CIFS在JAVA中的一个实现,是samba组织负责维护开发的一个开源项目,专注于使用java语言对cifs协议的设计和实现。他们将jcifs设计成为一个完整的,丰富的,具有可扩展能力且线程安全的客户端库。这一库可以应用于各种java虚拟机访问遵循CIFS/SMB网络传输协议的网络资源。类似于java.io.File的接口形式,在多线程的工作方式下被证明是有效而容易使用的。

它的资源url定位:smb://{user}:{password}@{host}/{path},smb为协议名,user和password分别为共享文件机子的登陆名和密码,@后面是要访问的资源的主机名或IP地址。最后是资源的共享文件夹名称和共享资源名。

Java 实现zip的解压和读取可以使用ZipInputStream 。

举例如下:

public static void downloadSmb(HttpServletResponse response,String filename,String zipFile) throws Exception{
try{
SmbFile smbFile = new SmbFile(zipFile);//zipFile是一个包含服务器IP和路径的完整url
System.out.println("smbFile:--"+zipFile);
SmbFileInputStream in = new SmbFileInputStream(smbFile);
ZipInputStream zip = new ZipInputStream(in);
ZipEntry entry = null;
boolean exist = false;
while((entry = zip.getNextEntry()) != null)
{
System.out.println(entry.getName());
if(entry.getName().equals(filename)){
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + filename);
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
int n;
while((n = zip.read(b)) != -1)
{
out.write(b, 0, n);
}
out.flush();
out.close();
exist = true;
break;
}
}
zip.close();
if(!exist){
throw new Exception("not find path");
}
}catch (Exception e) {
e.printStackTrace();
throw e;
}

}


主要步骤就是定义一个SmbFile ,将它读到SmbFileInputStream流,通过ZipInputStream流,遍历文件名,获取到想要的指定文件以后,以字节方式读出,在输出到客户端就完成了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: