设为首页 收藏本站
查看: 1426|回复: 0

[经验分享] java 两个通过java代码操作FTP的类,上传下载删除,获取文件

[复制链接]

尚未签到

发表于 2016-6-10 10:30:37 | 显示全部楼层 |阅读模式
1.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
public class FtpBusiness {
private final static Log logger = LogFactory.getLog(FtpBusiness.class);
/**
* 创建连接
*
* @param IP FTP服务器地址
* @param userName FTP服务器用户名
* @param passWord FTP服务器密码
* @return
* @throws Exception
*/
public FtpClient ftpConnection(String IP, String userName, String passWord)
throws Exception {
FtpClient fc = null;
try {
fc = new FtpClient();
fc.openServer(IP);
fc.login(userName, passWord);
fc.binary();
} catch (Exception e) {
logger.error(e);
}
return fc;
}
/**
* 关闭连接
*
* @param fc FTP连接对象
* @return
*/
public boolean ftpClose(FtpClient fc) {
try {
fc.closeServer();
} catch (Exception e) {
logger.error(e);
return false;
}
return true;
}
/**
* 获取当前目录
*
* @param fc FTP连接对象
* @return
*/
public String ftpPWD(FtpClient fc){
try {
return fc.pwd();
} catch (Exception e) {
logger.error(e);
return null;
}
}
public void ftpCD(FtpClient fc, String path){
try {
fc.cd(path);
} catch (Exception e) {
logger.error("FTP 转换到目录" + path + "异常:" + e);
}
}
/**
* 获取文件列表
*
* @param fc FTP连接对象
* @return
* @throws Exception
*/
public String ftpList(FtpClient fc){
try {
TelnetInputStream is = fc.list();
StringBuffer sb = new StringBuffer();
int k;
while ((k = is.read()) != -1) {
sb.append((char) k);
}
is.close();
return new String(sb.toString().getBytes("iso-8859-1"), "GBK");
} catch (Exception e) {
logger.error(e);
return null;
}
}
/**
* 下载文件
*
* @param fc FTP连接对象
* @param filename 下载的文件名称
* @return
* @throws Exception
*/
public InputStream getFile(FtpClient fc, String filename){
InputStream is = null;
try {
fc.binary();
is = fc.get(filename);
return is;
} catch (Exception e) {
logger.error("下载文件:" + filename + " 异常");
return null;
}
}
/**
* 上传文件
*
* @param fc FTP连接对象
* @param filename  上传的文件名称
* @return
* @throws IOException
*/
public boolean ftpPut(FtpClient fc, String filename, String Url) {
FileInputStream is = null;
TelnetOutputStream os = null;
try {
os = fc.put(filename);
File file_in = new File(Url);
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} catch (IOException ex) {
logger.error(ex);
return false;
} finally {
try {
is.close();
os.close();
} catch (Exception e) {
logger.error(e);
}
}
return true;
}
/**
* 删除文件
*
* @param fc FTP连接对象
* @param filename 删除的文件名称
* @return
*/
public boolean ftpDelete(FtpClient fc, String filename) {
try {
fc.cd(ftpPWD(fc));
} catch (IOException e) {
logger.error(e);
return false;
}
fc.sendServer("dele " + filename + "\r\n");
try {
fc.readServerResponse();
} catch (IOException e) {
logger.error(e);
}
return true;
}
public static void main(String[] args) throws Exception {
String IP = "111.222.333.444";
String userName = "testftpU";
String userPassword = "testftpP";
FtpClient fc = null;
String fileList = "";
// 文件名为项目路径下的文件
String upFileName = "d:\\a.txt";
String dictionary = "";
FtpBusiness ftp = new FtpBusiness();
// 链接FTP
fc = ftp.ftpConnection(IP, userName, userPassword);
// 获得文件列表
fileList = ftp.ftpList(fc);
logger.info("当前文件列表:\n" + fileList);
// 获得当前目录
dictionary = ftp.ftpPWD(fc);
logger.info("当前目录:" + dictionary);
// 上传文件
ftp.ftpPut(fc, upFileName, "d:\\a.txt");
// 下载文件
// ftp.getFile(fc, "b.txt");
// 删除文件
// ftp.ftpDelete(fc, "PSS.rar");
// 关闭连接
ftp.ftpClose(fc);
}
}


2

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class ftpTest {
/**
* 获得连接-FTP方式
* @param hostname FTP服务器地址
* @param port FTP服务器端口
* @param username FTP登录用户名
* @param password FTP登录密码
* @return FTPClient
*/
public FTPClient getConnectionFTP(String hostName, int port, String userName, String passWord) {
//创建FTPClient对象
FTPClient ftp = new FTPClient();
try {
//连接FTP服务器
ftp.connect(hostName, port);
//下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
//登录ftp
ftp.login(userName, passWord);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
System.out.println("连接服务器失败");
}
System.out.println("登陆服务器成功");
} catch (IOException e) {
e.printStackTrace();
}
return ftp;
}
/**
* 关闭连接-FTP方式
* @param ftp FTPClient对象
* @return boolean
*/
public boolean closeFTP(FTPClient ftp) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
System.out.println("ftp已经关闭");
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
/**
* 上传文件-FTP方式
* @param ftp FTPClient对象
* @param path FTP服务器上传地址
* @param filename 本地文件路径
* @param inputStream 输入流
* @return boolean
*/
public boolean uploadFile(FTPClient ftp, String path, String fileName, InputStream inputStream) {
boolean success = false;
try {
ftp.changeWorkingDirectory(path);//转移到指定FTP服务器目录
FTPFile[] fs = ftp.listFiles();//得到目录的相应文件列表
fileName = ftpTest.changeName(fileName, fs);
fileName = new String(fileName.getBytes("GBK"),"ISO-8859-1");
path = new String(path.getBytes("GBK"), "ISO-8859-1");
//转到指定上传目录
ftp.changeWorkingDirectory(path);
//将上传文件存储到指定目录
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//如果缺省该句 传输txt正常 但图片和其他格式的文件传输出现乱码
ftp.storeFile(fileName, inputStream);
//关闭输入流
inputStream.close();
//退出ftp
ftp.logout();
//表示上传成功
success = true;
System.out.println("上传成功。。。。。。");
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
/**
* 删除文件-FTP方式
* @param ftp FTPClient对象
* @param path FTP服务器上传地址
* @param filename FTP服务器上要删除的文件名
* @return
*/
public boolean deleteFile(FTPClient ftp, String path, String fileName) {
boolean success = false;
try {
ftp.changeWorkingDirectory(path);//转移到指定FTP服务器目录
fileName = new String(fileName.getBytes("GBK"),"ISO-8859-1");
path = new String(path.getBytes("GBK"), "ISO-8859-1");
ftp.deleteFile(fileName);
ftp.logout();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
/**
* 上传文件-FTP方式
* @param ftp FTPClient对象
* @param path FTP服务器上传地址
* @param fileName 本地文件路径
* @param localPath 本里存储路径
* @return boolean
*/
public boolean downFile(FTPClient ftp, String path, String fileName, String localPath) {
boolean success = false;
try {
ftp.changeWorkingDirectory(path);//转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles(); //得到目录的相应文件列表
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "\\" + ff.getName());
OutputStream outputStream = new FileOutputStream(localFile);
//将文件保存到输出流outputStream中
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"), "ISO-8859-1"), outputStream);
outputStream.flush();
outputStream.close();
System.out.println("下载成功");
}
}
ftp.logout();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
/**
* 判断是否有重名文件
* @param fileName
* @param fs
* @return
*/
public static boolean isFileExist(String fileName, FTPFile[] fs) {
for (int i = 0; i < fs.length; i++) {
FTPFile ff = fs;
if (ff.getName().equals(fileName)) {
return true; //如果存在返回 正确信号
}
}
return false; //如果不存在返回错误信号
}
/**
* 根据重名判断的结果 生成新的文件的名称
* @param fileName
* @param fs
* @return
*/
public static String changeName(String fileName, FTPFile[] fs) {
int n = 0;
//fileName = fileName.append(fileName);
while (isFileExist(fileName.toString(), fs)) {
n++;
String a = "[" + n + "]";
int b = fileName.lastIndexOf(".");//最后一出现小数点的位置
int c = fileName.lastIndexOf("[");//最后一次"["出现的位置
if (c < 0) {
c = b;
}
StringBuffer name = new StringBuffer(fileName.substring(0, c));//文件的名字
StringBuffer suffix = new StringBuffer(fileName.substring(b + 1));//后缀的名称
fileName = name.append(a) + "." + suffix;
}
return fileName.toString();
}
/**
*
* @param args
*
* @throws FileNotFoundException
*
* 测试程序
*
*/
public static void main(String[] args) throws FileNotFoundException {
String path = "/home1/ftproot/textftp/test/";
File f1 = new File("d:\\a.txt");
String filename = f1.getName();
System.out.println(filename);
//InputStream input = new FileInputStream(f1);
//ftpTest a = new ftpTest();
//a.uploadFile("172.25.5.193", 21, "shiyanming", "123", path, filename, input);
/*
* String path ="D:\\ftpindex\\"; File f2 = new
* File("D:\\ftpindex\\old.txt"); String filename2= f2.getName();
* System.out.println(filename2); ftpTest a = new
* ftpTest(); a.downFile("172.25.5.193", 21, "shi", "123", path,
* filename2, "C:\\");
*/
ftpTest a = new ftpTest();
InputStream input = new FileInputStream(f1);
//a.uploadFile("218.108.250.205", 21, "hwyhftp", "!#hwyhftp", path, filename, input);
//a.deleteFile("218.108.250.205", 21, "hwyhftp", "!#hwyhftp", path, filename);
//a.downFile("218.108.250.205", 21, "hwyhftp", "!#hwyhftp", path, "欢[2].txt");
FTPClient ftp = a.getConnectionFTP("111.222.333.444", 21, "testU", "testP");
//a.deleteFile(ftp, path, "a[2].txt");
a.uploadFile(ftp, path, filename, input);
a.closeFTP(ftp);
}
}

黑色头发:http://heisetoufa.iyunv.com/

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-228547-1-1.html 上篇帖子: sun.net.ftp.FtpClient 实现简单上传下载 下篇帖子: ant checkout svn. 并ftp上传 运行远程命令
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表