【远程传输】java上传文件到共享文件夹

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/moshenglv/article/details/81676304
今天做到一个需求 是要用Java把文件上传到共享文件夹  下面是一个例子  以后备用
注:用到一个jar包 jcifs-1.3.14.jar  
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
 
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import jcifs.util.LogStream;
 
public class Smb {
       private static LogStream log = LogStream.getInstance();  //打印日志 
		private String url = "";       
		private SmbFile smbFile = null; 
		private SmbFileOutputStream smbOut = null; 
		private static Smb smb = null; //共享文件协议 
	
		public static synchronized Smb getInstance(String url) { 
		  if (smb == null) 
		   return new Smb(url); 
		  return smb; 
		} 
 
		/** 
		  * @param url服务器路径 
		  */ 
		private Smb(String url) { 
			  this.url = url; 
			  this.init(); 
		} 
 
		public void init() { 
			  try { 
				   log.println("开始连接...url:" + this.url); 
				   smbFile = new SmbFile(this.url); 
				   smbFile.connect(); 
				   log.println("连接成功...url:" + this.url); 
			  } catch (MalformedURLException e) { 
				  e.printStackTrace(); 
				  log.print(e); 
			  } catch (IOException e) { 
				   e.printStackTrace(); 
				   log.print(e); 
			  } 
		} 
 
		
 
		/** 
		  * 上传文件到服务器 
		  */ 
		public int uploadFile(File file) { 
			  int flag = -1; 
			  BufferedInputStream bf = null; 
			  try { 
				   smbOut = new SmbFileOutputStream(this.url + "/" + file.getName(), false); 
				   bf = new BufferedInputStream(new FileInputStream(file)); 
				   byte[] bt = new byte[8192]; 
				   int n = bf.read(bt); 
				   while (n != -1) { 
				    this.smbOut.write(bt, 0, n); 
				    this.smbOut.flush(); 
				    n = bf.read(bt); 
				   } 
				   flag = 0; 
				   log.println("文件传输结束..."); 
			  } catch (SmbException e) { 
				   e.printStackTrace(); 
				   log.println(e); 
			  } catch (MalformedURLException e) { 
				   e.printStackTrace(); 
				   log.println(e); 
			  } catch (UnknownHostException e) { 
				   e.printStackTrace(); 
				   log.println("找不到主机...url:" + this.url); 
			  } catch (IOException e) { 
				   e.printStackTrace(); 
				   log.println(e); 
			  } finally { 
				   try { 
				    if (null != this.smbOut) 
				     this.smbOut.close(); 
				    if (null != bf) 
				     bf.close(); 
				   } catch (Exception e2) { 
				    e2.printStackTrace(); 
				   } 
			  } 
	
			  return flag; 
		} 
		public static void main(String[] args) { 
			  //服務器地址 格式為 smb://电脑用户名:电脑密码@电脑IP地址/IP共享的文件夹 
			  String remoteUrl = "smb://niu:[email protected]/imashare/";  
			  String localFile = "C:/Users/niu/Desktop/all/GFS_170221_093426.txt";  //本地要上传的文件 
			  File file = new File(localFile); 
			  Smb smb = Smb.getInstance(remoteUrl); 
			  smb.uploadFile(file);// 上传文件 
		}
		
	}
 

猜你喜欢

转载自blog.csdn.net/moshenglv/article/details/81676304