1、所需jar包:jcifs-1.3.17.jar
2、基础类
/**
* Smb工具类
* @author Shane.C
*
*/
public class Smb {
private static LogStream log = new LogStream(System.out);
private SmbFile smbFile = null;
private Smb(String remoteUrl) throws IOException {
super();
smbFile = new SmbFile(remoteUrl);
init();
}
/**
* 初始化测试
* @throws IOException
*/
private void init() throws IOException {
log.print("测试连接中。。。");
smbFile.connect();
log.print("连接成功!");
}
/**
* 根据Url读取共享文件夹
* @param RemoteUrl 例:上传 :smb://用户名:密码@终端ip/共享文件夹名称;
* 下载:smb://用户名:密码@终端ip/共享文件夹名称/../下载文件:
* @return
* @throws IOException
*/
public SmbFile getSmbFile(String remoteUrl) throws IOException{
return new Smb(remoteUrl).smbFile;
}
/**
* 根据 俩路径完成文件上传
* @param localFile 例: 上传文件路径
* @param remoteFile 上传 :smb://用户名:密码@终端ip/共享文件夹名称;
*/
public void uploadSmbFile(String localFile,String remoteFile) {
InputStream in = null;
OutputStream out = null;
byte[] buffer = new byte[2048];
int len = 0;
try {
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(getSmbFile(remoteFile)));
while((len=in.read(buffer,0,buffer.length))!=-1){
out.write(buffer, 0, len);
}
out.flush();
log.print("smb 上传文件成功!");
} catch (Exception e) {
log.print("smb:uploadSmbFile 失败!"+e.getMessage());
}finally {
try {
if(in!=null) {
in.close();
}
if(out!=null) {
out.close();
}
} catch (IOException e) {
log.print("关闭 IO发生异常!"+e.getMessage());
}
}
}
/**
* 根据 俩路径完成文件下载
* @param remoteFile 下载:smb://用户名:密码@终端ip/共享文件夹名称/../下载文件:
* @param localFile 下载:本机下载地址
*/
public void downLoadSmbFile(String remoteFile,String localFile) {
InputStream in = null;
OutputStream out = null;
byte[] buffer = new byte[2048];
int len = 0;
try {
in = new BufferedInputStream(new SmbFileInputStream(getSmbFile(remoteFile)));
out = new BufferedOutputStream(new FileOutputStream(localFile));
while((len=in.read(buffer,0,buffer.length))!=-1){
out.write(buffer, 0, len);
}
out.flush();
log.print("smb 下载文件成功!");
} catch (Exception e) {
log.print("smb:downLoadSmbFile 失败!"+e.getMessage());
}finally {
try {
if(in!=null) {
in.close();
}
if(out!=null) {
out.close();
}
} catch (IOException e) {
log.print("关闭 IO发生异常!"+e.getMessage());
}
}
}
}
3、此处有坑
The netWork name cont be found. :未找到共享文件夹。
正常情况会在 我的电脑> 管理> 共享文件夹>共享 中找到 使用的文件夹。
如果未找到文件夹 按如下设置
有共享文件夹但连接不上