往ftp 服务器写文件,往ftp 上写文件

使用sun提供的jar 往ftp上写文件

public class FtpFileManager {

FtpClient ftpclient;

Logger log4j=Logger.getLogger(FtpFileManager.class);

private boolean connectServer(){

String serverName=Constants.getParamVal("ftp.server","");

String userName=Constants.getParamVal("ftp.user","");

String password=Constants.getParamVal("ftp.password","");

int port=21;

try{

port=Integer.parseInt(Constants.getParamVal("ftp.port","21"));

}catch(NumberFormatException e){

log4j.error("config.properties 文件中,ftp端口必须设置为数字", e);

}

try {

ftpclient=new FtpClient();

ftpclient.openServer(serverName, port);

ftpclient.login(userName, password);

ftpclient.binary();  // 二进制传输

} catch (IOException e) {

log4j.error("ftp服务器登陆失败,IP="+serverName+",userName="+userName+"password="+password, e);

return false;

}

return true;

}

/**

*  往ftp服务器上写文件

* @param path

* @param filename

* @param content

* @throws IOException

*/

private void saveFileToServer(String path,String filename,String content) throws IOException{

TelnetOutputStream out=null;

InputStream in=null;

try{

try{

ftpclient.cd(path);

}catch(FileNotFoundException e){

ftpclient.sendServer("XMKD"+path+"\r\n");  // 新建路径

ftpclient.readServerResponse();

ftpclient.cd(path);

}

out=ftpclient.put(filename);

byte[] bytes=content.getBytes();

in=new ByteArrayInputStream(bytes);

IOUtils.copy(in, out);

}catch(Exception e){

log4j.error("ftp  写文件时异常,文件名:"+filename,e);

}finally{

if(in!=null){

in.close();

}

if(out!=null){

out.close();

}

}

}

/**

*  文件上传

* @param path

* @param filename

* @param content

*/

public void upload(String path,String filename,String content){

try {

this.connectServer();

this.saveFileToServer(path, filename, content);

} catch (IOException e) {

log4j.error("IO 流关闭异常", e);

}finally{

this.logout();

}

}

/**

*  关闭ftp

*/

private void logout(){

if(ftpclient.serverIsOpen()){

try {

ftpclient.closeServer();

} catch (IOException e) {

log4j.error("关闭ftp 时异常", e);

}

}

}

public static void main(String[] args) {

FtpFileManager f=new FtpFileManager();

f.upload("a", "1.txt", "130");

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值