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

JAVA实现上传下载共享文件

2015-09-11 14:34 417 查看
1、上传下载共享文件需要用到jcifs,先下载相关JAR包(开源项目的源码,demo,文挡、API应有尽有)
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: