apache.common.net.ftp
NOT sun.net.ftp
代码摘自:http://blog.csdn.net/techbirds_bao/article/details/8593706
public class FtpTest{
/**
*向ftp写文件
*/
public boolean uploadFile(
String content, //要写入的内容
String username, //ftp登录用户名
String password, //ftp登录密码
String hostname, //主机名 ,ip
String filename, //创建的文件名
String path //指定写入目录
){
boolean flag = false;
FTPClient ftpClient = new FTPClient();
try{
InputStream is = null;
int reply;
//1.输入流
is = new ByteArrayInputStream(content.getBytes());
//2.连接服务器,采用默认端口21
ftpClient.connect(hostname);
//3.登录ftp
ftpClient.login(username , password);
reply = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
return flag;
}
//4.指定写入的目录
ftpClient.changeWorkingDirectory(path);
//5.写操作
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(new String(filename.getBytes("utf-8"),"iso-8859-1"),is);
is.close();
//退出
ftp.logout();
flag = true;
}catche(Exception e)
{
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
}
return flag;
}
}
/**
*下载与上传一致,只是一个是写,一个是读
*/
......
//指定要下载的目录
ftpClient.changeWorkingDirectory(path);
FTPFile[] fs = ftp.listFiles();//目录下的文件list
for(FTPFile ff:fs){
byte[] bytes = ff.getName().getBytes("iso-8859-1");
String fn = new String(bytes , "utf-8");
if(fn.equals(fileName)){ //判断是否是要下载的文件fileName
File localFile = new File(localPath + ff.getName());//localPath 本地存储的目录
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName() , is);
is.close();
}
}
根据需求,我尝试了写文件的一些不同情况
/*
写文件apkInfoFileName:
若文件不存在,则新建文件apkInfoFileName,写入内容versionCode+path;
若文件存在,则向文件中追加内容"\n"+versionCode+path;
*/
OutputStreamWriter out = new OutputStreamWriter(ftp.appendFileStream(apkInfoFileName));
BufferedWriter bw = new BufferedWriter(out);
bw.write("\n"+versionCode+path);
bw.flush();
bw.close();
out.close();
发现上传不上去,有这几点原因
防火墙
环境:Centos7
我在杂项里找到防火墙,点击区域里的public,勾上ftp
FTPClient.enterLocalPassiveMode()
FTPClient连接前调用FTPClient.enterLocalPassiveMode();这个方法的意思就是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据。为什么要这样做呢,因为ftp server可能每次开启不同的端口来传输数据,但是在linux上,由于安全限制,可能某些端口没有开启,所以就出现阻塞。
MORE
listDirectories();
listnames()