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

[经验分享] Java实现FTP上传下载功能

[复制链接]

尚未签到

发表于 2015-11-6 10:28:56 | 显示全部楼层 |阅读模式
  http://lavasoft.blog.iyunv.com/62575/93883/
  

Java FTP客户端工具包很多,在此我选用的Apache的FTPClient。这个包的获取可以通过http://commons.apache.org/net/来获取,我使用的是最新的commons-net-1.4.1.zip。其中包含了众多的java网络编程的工具包,官方文档列举如下:
    支持网络协议如下:
        FTP
        NNTP
        SMTP
        POP3
        Telnet
        TFTP
        Finger
        Whois
        rexec/rcmd/rlogin
        Time (rdate) and Daytime
        Echo
        Discard
        NTP/SNTP
都很有用。在此我用到的是FTP相关的一些包。
public class FtpTest {
public static void main(String[] args) {
testUpload();
testDownload();
}
/**
* FTP上传单个文件测试
*/
public static void testUpload() {
FTPClient ftpClient
= new FTPClient();
FileInputStream fis
= null;
try {
ftpClient.connect(
"192.168.14.117");
ftpClient.login(
"admin", "123");
File srcFile
= new File("C:\\new.gif");
fis
= new FileInputStream(srcFile);
//设置上传目录
ftpClient.changeWorkingDirectory("/admin/pic");
ftpClient.setBufferSize(
1024);
ftpClient.setControlEncoding(
"GBK");
//设置文件类型(二进制)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(
"3.gif", fis);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
}
finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
/**
* FTP下载单个文件测试
*/
public static void testDownload() {
FTPClient ftpClient
= new FTPClient();
FileOutputStream fos
= null;
try {
ftpClient.connect(
"192.168.14.117");
ftpClient.login(
"admin", "123");
String remoteFileName
= "/admin/pic/3.gif";
fos
= new FileOutputStream("c:/down.gif");
ftpClient.setBufferSize(
1024);
//设置文件类型(二进制)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(remoteFileName, fos);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
}
finally {
IOUtils.closeQuietly(fos);
try {
ftpClient.disconnect();
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
}

  

DSC0000.gif DSC0001.gif
public class Ftp {
private static final Logger logger = Logger.getLogger(FTP.class);
/**
* FTP客户端
*/
private FtpClient ftpClient;
/**
* 服务器连接
*
*
@param ip
*            服务器IP
*
@param port
*            服务器端口
*
@param user
*            用户名
*
@param password
*            密码
*
@param path
*            服务器路径
*
@throws IOException
*
*/
public void connectServer(String ip, int port, String user, String password, String path) throws IOException {
try {
System.out.println(
"ftp connect...");
ftpClient
= new FtpClient(ip);
ftpClient.login(user, password);
// 设置成2进制传输
            ftpClient.binary();
System.out.println(
"ftp login success!");
if (path.length() != 0) {
// 把远程系统上的目录切换到参数path所指定的目录
try {
ftpClient.cd(path);
}
catch (Exception e) {
throw new IOException("FTP server: 550 CWD failed 远程目录未响应", e);
}
}
ftpClient.binary();
}
catch (IOException e) {
logger.error(
"ftp connect err!");
logger.error(e.getMessage());
e.printStackTrace();
throw new IOException(e.getMessage());
}
}
/**
* 关闭连接
*
*
*/
public void closeConnect() {
try {
ftpClient.closeServer();
System.out.println(
"closeConnect success");
}
catch (IOException ex) {
System.out.println(
"not closeConnect");
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* 上传文件
*
*
@param localFile
*            本地文件
*
@param remoteFile
*            远程文件
*
*/
public void upload(String localFile, String remoteFile) {
TelnetOutputStream os
= null;
FileInputStream is
= null;
try {
// 将远程文件加入输出流中
os = ftpClient.put(remoteFile);
// 获取本地文件的输入流
File file_in = new File(localFile);
is
= new FileInputStream(file_in);
// 创建一个缓冲区
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes,
0, c);
}
System.out.println(
"upload success");
}
catch (IOException ex) {
System.out.println(
"not upload");
ex.printStackTrace();
throw new RuntimeException(ex);
}
finally {
try {
if (is != null) {
is.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (os != null) {
os.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 下载文件
*
*
@param remoteFile
*            远程文件路径(服务器端)
*
@param localFile
*            本地文件路径(客户端)
*
*/
public void download(String remoteFile, String localFile) {
TelnetInputStream is
= null;
FileOutputStream os
= null;
try {
// 获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
is = ftpClient.get(remoteFile);
File file_in
= new File(localFile);
os
= new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes,
0, c);
}
System.out.println(
"download success");
}
catch (IOException ex) {
System.out.println(
"not download");
ex.printStackTrace();
throw new RuntimeException(ex);
}
finally {
try {
if (is != null) {
is.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (os != null) {
os.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 返回FTP目录下的文件列表
*
*
@param ftpDirectory
*
@return
*/
public List<String> getFileNameList(String ftpDirectory) {
List
<String> list = new ArrayList<String>();
BufferedReader bf
= null;
InputStreamReader isr
= null;
DataInputStream ds
= null;
try {
ds
= new DataInputStream(ftpClient.nameList(ftpDirectory));
isr
= new InputStreamReader(ds);
bf
= new BufferedReader(isr);
String filename
= "";
while ((filename = bf.readLine()) != null) {
list.add(filename);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
ds.close();
}
catch (IOException e) {
e.printStackTrace();
}
try {
isr.close();
}
catch (IOException e) {
e.printStackTrace();
}
try {
bf.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return list;
}
public static void main(String agrs[]) throws Exception {
Ftp ftp
= new Ftp();
ftp.connectServer(
"192.168.1.221", 21, "admin", "123@123", "/FTP Files/temp");
List
<String> list = ftp.getFileNameList("/FTP Files/temp");
for (String str : list) {
try {
Calendar cal
= Calendar.getInstance();// 使用日历类
int year = cal.get(Calendar.YEAR);// 得到年
int month = cal.get(Calendar.MONTH) + 1;// 得到月,因为从0开始的,所以要加1
int day = cal.get(Calendar.DAY_OF_MONTH);// 得到天
String fileName = "WiMAX_" + year + month + day;
System.out.println(
"str" + str + "---------" + "fileName:" + fileName);
String regEx
= "WiMAX_\\d{8}_\\d{5}_\\s{5}"; // 表示a或F
Pattern pat = Pattern.compile(regEx);
System.out.println(pat.matcher(str).find());
// if (str.contains(fileName)) {
// fu.download("/FTP Files/temp/" + str, "d:/temp/" + str);
// System.out.println("download:" + str);
// }

}
catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
throw e;
}
}

ftp.closeConnect();
}
}

View Code   

版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 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-135796-1-1.html 上篇帖子: C# FTP下载一目录下所有文件夹及文件 下篇帖子: Python 提取文件,备份,压缩,并上传到远程FTP后,清空指定时间范围外的文件
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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