前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java ftp上传方法

java ftp上传方法

作者头像
用户5640963
发布2019-07-25 11:36:05
3.8K0
发布2019-07-25 11:36:05
举报
文章被收录于专栏:卯金刀GG卯金刀GG

提供一个思路,大家可以参考着修改自己的方法!

/** * 上传文件到FTP * * @param file * file文件,struts2从页面得到的File类型 * * @param filePath * 要保存在FTP上的路径(文件夹) * @param fileName * * * @return 文件是否上传成功 * * @throws Exception */

public static boolean upload(File file, String filePath, String fileName) {

TelnetOutputStream to = null;

FileInputStream fi = null;

filePath = FILE_SEPARATOR (定义的路径获取)+ filePath;

try { if (file != null) {

connectFTP(); // ftpClient.setAsciiType();

if (!isDirExist(filePath.replace("\\", "/"))) {

createDir(filePath.replace("\\", "/"));

ftpClient.changeDirectory("/" + filePath.replace("\\", "/"));

}

fi = new FileInputStream(file);

to = (TelnetOutputStream) ftpClient.putFileStream(fileName, true);

byte[] bytes = new

byte[1024];

int i = fi.read(bytes);

while (i != -1) {

to.write(bytes);

i = fi.read(bytes); } }

return true;

} catch (FileNotFoundException e1) { e1.printStackTrace(); return false;

} catch (IOException e2) { e2.printStackTrace(); return false;

} catch (Exception e) { e.printStackTrace(); return false;

} finally {

if (fi != null) {

try { fi.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (to != null) {

try { to.flush();

to.close();

} catch (IOException e) { e.printStackTrace(); }

}

closeFTP();

}

}

/** * 链接FTP * * @throws FtpProtocolException */

public static void connectFTP() throws

FtpProtocolException {

try

{

ftpClient = FtpClient.create();

ftpClient.connect(new InetSocketAddress(url, port));

ftpClient.login(user, password.toCharArray());

ftpClient.setBinaryType();

} catch

(IOException e) {

e.printStackTrace();

}

}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档