import java.io.*;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
public class Main {
/**
* 从本地上传文件到共享目录
* @param remoteUrl 共享文件目录
* @param localFilePath 本地文件绝对路径
*/
public void smbPut(String remoteUrl, String localFilePath)
{
InputStream in = null;
OutputStream out = null;
try
{
File localFile = new File(localFilePath);
String fileName = localFile.getName();
SmbFile remoteFile = new SmbFile(remoteUrl+"/"+ fileName);
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
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();
}
}
}
/**
* 从共享目录拷贝文件到本地
* @param remoteUrl 共享目录上的文件路径
* @param localDir 本地目录
*/
public void smbGet(String remoteUrl, String localDir)
{
InputStream in = null;
OutputStream out = null;
try
{
SmbFile remoteFile = new SmbFile(remoteUrl);
//这一句很重要
remoteFile.connect();
if (remoteFile == null)
{
System.out.println("共享文件不存在");
return;
}
String fileName = remoteFile.getName();
File localFile = new File(localDir + File.separator + fileName);
System.out.println(localFile.getAbsolutePath());
if(!localFile.exists())
{
localFile.createNewFile();
}
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();
}
}
}
public static void main(String[] args)
{
Main test = new Main();
//本地上传到共享目录
//smb://用户名:密码@地址/目录
test.smbPut("smb://chenhong:chenhong@192.168.1.104/shared","/Users/chenhong/Documents/shared/2.java");
//从共享目录下载到本地
//smb://用户名:密码@地址/目录/文件
test.smbGet("smb://chenhong:chenhong@192.168.1.104/shared/1.log","/Users/chenhong/Documents/shared");
System.out.println("成功");
}
}