Java 用JCIFS访问网络文件共享





如果设置win7下的局域网文件共享可以查看一下链接:



​ http://jingyan.baidu.com/article/fec7a1e53efe621190b4e7ae.html ​

{  

/**
* 从共享目录拷贝文件到本地
* @param remoteUrl 共享目录上的文件路径
* @param localDir 本地目录
*/
public void
{
null;
null;
try
{
new
//这一句很重要
remoteFile.connect();
if (remoteFile == null)
{
"共享文件不存在");
return;
}
String fileName = remoteFile.getName();
new
new BufferedInputStream(new
new BufferedOutputStream(new
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1)
{
out.write(buffer);
new byte[1024];
}
}
catch
{
e.printStackTrace();
}
finally
{
try
{
out.close();
in.close();
}
catch
{
e.printStackTrace();
}
}
}

/**
* 从本地上传文件到共享目录
* @Version1.0 Sep 25, 2009 3:49:00 PM
* @param remoteUrl 共享文件目录
* @param localFilePath 本地文件绝对路径
*/
public void
{
null;
null;
try
{
new

String fileName = localFile.getName();
new SmbFile(remoteUrl + "/"
new BufferedInputStream(new
new BufferedOutputStream(new
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1)
{
out.write(buffer);
new byte[1024];
}
}
catch
{
e.printStackTrace();
}
finally
{
try
{
out.close();
in.close();
}
catch
{
e.printStackTrace();
}
}
}

public static void
{
new
// smb:域名;用户名:密码@目的IP/文件夹/文件名.xxx
// test.smbGet("smb://szpcg;jiang.t:xxx@192.168.193.13/Jake/test.txt",
// "c://") ;

// test.smbPut("smb://szpcg;jiang.t:xxx@192.168.193.13/Jake",
// "c://test.txt");


//用户名密码不能有强字符,也就是不能有特殊字符,否则会被作为分断处理
"smb://CHINA;xieruilin:123456Xrl@10.70.36.121/project/report/网上问题智能分析助手使用文档.doc",
"c://Temp/");

}

}




需要导入包jcifs-1.3.15.jar



public String storeByRmoeteFilename(String ip,String name,String password,String filePath,String filename, MultipartFile file) throws IOException
{
<span style="color:#ff0000;">NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(ip, name, password);</span>
SmbFile smbFile;
try {
<span style="color:#ff6666;">smbFile = new SmbFile(filePath,auth);
if (!smbFile.exists()) {
smbFile.mkdirs();
}</span>
} catch (MalformedURLException e) {
logger.error(e.getMessage());
e.printStackTrace();
} catch (SmbException e) {
logger.error(e.getMessage());
e.printStackTrace();
throw e;
}
InputStream in = null;
OutputStream out = null;
try {
smbFile = new SmbFile(filePath+filename,auth);
if(!smbFile.exists()){
smbFile.createNewFile();
}
in = file.getInputStream();
out = smbFile.getOutputStream();
byte[] buffer = new byte[1024*10];
int i = 0;
long uploadSize =0;
while((i=in.read(buffer))!=-1){//in对象的read方法返回-1为 文件以读取完毕
out.write(buffer, 0, i);
uploadSize = uploadSize+i;
buffer = new byte[1024*10];
}
out.flush();
in.close();
out.close();
} catch (MalformedURLException e) {
logger.error(e.getMessage());
}catch (SmbException e) {
logger.info("服务器磁盘空间不足:"+e);
} catch (IOException e) {
logger.error(e.getMessage());
if (null!=in) {
try {
in.close();
} catch (IOException e1) {
logger.error(e.getMessage());
}
}
if (null!=out) {
try {
in.close();
} catch (IOException e1) {
logger.error(e.getMessage());
}
}
throw e;
}
return filename;
}