我们需要一个jar包
jcifs-1.3.19.jar
/**
*
* @param remoteUrl 远程路径
* @param newFilePath 文件路径
* @param content 写入内容
*/
public void smbPut(String remoteUrl,String newFilePath,String content){
try {
OutputStream out = null;
if(newFilePath.lastIndexOf("/")==-1){
System.out.println("newFilePath的格式不对");
return;
}
//文件夹路径 datafolder
String folder = newFilePath.substring(0, newFilePath.lastIndexOf("/"));
//新建远程的文件夹
SmbFile remoteFile = new SmbFile(remoteUrl + "/" + folder);
//判断文件夹是否存在,否则创建
if(!remoteFile.exists()){
remoteFile.mkdir();
}
//新建远程文件
remoteFile = new SmbFile(remoteUrl + "/" + newFilePath);
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
//使用输出流写入内容
byte[] buffer = content.getBytes("utf-8");
for (byte b : buffer) {
out.write(b);
buffer = new byte[1024];
}
//关闭资源
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testSmb(){
//remoteUrl: sub:域名;用户名:密码@目标ip/文件夹
//newFilePath: aa/bb/cc/data.txt 或者/data.txt
smbPut("smb://username:pwd@202.117.114.54/datafolder", "aa/bb/cc/data.txt", "内容");
}