java基于jcifs.smb实现远程发送文件到服务器
程序员文章站
2023-12-13 09:41:58
本文实例为大家分享了java实现远程发送文件到服务器的具体代码,供大家参考,具体内容如下
1.依赖的相关jar包  ...
本文实例为大家分享了java实现远程发送文件到服务器的具体代码,供大家参考,具体内容如下
1.依赖的相关jar包 jcifs-1.3.14.1.jar
2.创建smb的声明
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; public class smbutil { // 1. 声明属性 private string url = "smb://username:password@192.168.2.153/mars/"; private smbfile smbfile = null; private smbfileoutputstream smbout = null; private static smbutil smbutil = null; // 共享文件协议 private smbutil(string url) { this.url = url; this.init(); } // 2. 得到smbutil和连接的方法 public static synchronized smbutil getinstance(string url) { if (smbutil == null) return new smbutil(url); return smbutil; } // 3.smbfile连接 public void init() { try { system.out.println("开始连接...url:" + this.url); smbfile = new smbfile(this.url); smbfile.connect(); system.out.println("连接成功...url:" + this.url); } catch (malformedurlexception e) { e.printstacktrace(); system.out.print(e); } catch (ioexception e) { e.printstacktrace(); system.out.print(e); } } // 4.上传文件到服务器 public int uploadfile(file file) { int flag = -1; bufferedinputstream bf = null; try { this.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; system.out.println("文件传输结束..."); } catch (smbexception e) { e.printstacktrace(); system.out.println(e); } catch (malformedurlexception e) { e.printstacktrace(); system.out.println(e); } catch (unknownhostexception e) { e.printstacktrace(); system.out.println("找不到主机...url:" + this.url); } catch (ioexception e) { e.printstacktrace(); system.out.println(e); } finally { try { if (null != this.smbout) this.smbout.close(); if (null != bf) bf.close(); } catch (exception e2) { e2.printstacktrace(); } } return flag; } // 5. 在main方法里面测试 public static void main(string[] args) { // 服務器地址 格式為 smb://电脑用户名:电脑密码@电脑ip地址/ip共享的文件夹 string remoteurl = "smb://wangqinghua:wqh123@192.168.2.153/mars/"; string localfile = "f:/开关生产销售企业名录.xls"; // 本地要上传的文件 file file = new file(localfile); smbutil smb = smbutil.getinstance(remoteurl); smb.uploadfile(file);// 上传文件 } }
需要注意的事项:
以上是基于局域网,且上传文件的目录或者文件夹必须设置为共享模式。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。