java 上传远程服务器_java上传文件到远程服务器下的共享文件夹

[size=x-large]1. 导入jcifs-1.3.14.1.jar架包,创建类Smb

2. 声明属性

private static LogStream log = LogStream.getInstance();  //打印日志

private String url = "";

private SmbFile smbFile = null;

private SmbFileOutputStream smbOut = null;

private static Smb smb = null; //共享文件协议

3. 得到Smb和连接的方法

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);

}

}

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;

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;

}

5. 在main方法里面测试

public static void main(String[] args) {

//服務器地址 格式為 smb://电脑用户名:电脑密码@电脑IP地址/IP共享的文件夹

String remoteUrl = "smb://huangyuewang:iso@127.0.0.1/iso";

String localFile = "F:/宏茂达/资料/网友/fa8b64f05061c673730eec51.jpg";  //本地要上传的文件

File file = new File(localFile);

Smb smb = Smb.getInstance(remoteUrl);

smb.uploadFile(file);// 上传文件

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值