java访问远程共享文件

本文介绍了Microsoft的网络文件/打印服务系统SMB协议及后续的CIFS协议,并详细讲解了jcifs作为CIFS协议在Java中的实现方式。jcifs是由Samba组织维护的开源项目,适用于多种Java虚拟机环境,提供了丰富的API来访问网络资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自:http://hu-bj.javaeye.com/blog/327198
使用开源库JCIFS
http://jcifs.samba.org/
  Microsoft使用NetBIOS实现了一个网络文件/打印服
务系统,这个系统基于NetBIOS设定了一套文件共享协议,Microsoft称之为SMB(
Server Message Block)协议。这个协议被Microsoft用于它们Lan Manager和Wi
ndows NT服务器系统中,而Windows系统均包括这个协议的客户软件,因而这个协
议在局域网系统中影响很大。
  随着Internet的流行,Microsoft希望将这个协议扩展到Internet上去,成为
Inter net上计算机之间相互共享数据的一种标准。因此它将原有的几乎没有多少
技术文档的SMB协议进行整理,重新命名为 CIFS(Common Internet File Syste
m),并打算将它与NetBIOS相脱离,试图使它成为Internet上的一个标准协议。
  jcifs是CIFS在JAVA中的一个实现,是samba组织负责维护开发的一个开源项目,
专注于使用java语言对cifs协议的设计和实现。他们将jcifs设计成为一个完整的,丰
富的,具有可扩展能力且线程安全的客户端库。这一库可以应用于各种java虚拟机访
问遵循CIFS/SMB网络传输协议的网络资源。
示例:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
public class RemoteShareFile {
public static void main(String[] args) {
String smbMachine="smb://用户名:密码@IP地址/目录/文件名";
String localPath="D://";
File file=readFromSmb(smbMachine,localPath);
}
public static File readFromSmb(String smbMachine,String localpath){
File localfile=null;
InputStream bis=null;
OutputStream bos=null;
try {
SmbFile rmifile = new SmbFile(smbMachine);
String filename=rmifile.getName();
bis=new BufferedInputStream(new SmbFileInputStream(rmifile));
localfile=new File(localpath+File.separator+filename);
bos=new BufferedOutputStream(new FileOutputStream(localfile));
int length=rmifile.getContentLength();
byte[] buffer=new byte[length];
Date date=new Date();
bis.read(buffer);
bos.write(buffer);
Date end=new Date();
int time= (int) ((end.getTime()-date.getTime())/1000);
if(time>0)
System.out.println("用时:"+time+"秒 "+"速度:"+length/time/1024+"kb/秒");
} catch (Exception e){
System.out.println(e.getMessage());
}finally{
try {
bos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return localfile;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值