用代码打开FTP(1)
下载ftp服务器上的文件可以选择使用一些软件,也可以根据业务需要自己写代码。
一、对于数据量不大的ftp文件下载
1.以FTPClient类登录服务并获取ftpclient
package com.trgis.wisdomtour.utils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FtpConnectUtil { // ftp登录用户名 static private String userName=""; // ftp登录密码 static private String passWord=""; // ftp地址:直接IP地址 static private String server=""; static FTPClient FTPClient = null; public static FTPClient getFtp(){ if(FTPClient == null){ FTPClient ftp = new FTPClient(); FTPClient = ftp; String path = "/"; int reply; try{ //1.连接服务器 FTPClient.connect(server); // 设置默认超时时间 FTPClient.setDefaultTimeout(10 * 60 * 10000); // 设置连接超时时间 FTPClient.setConnectTimeout(10 * 60 * 10000); // 设置数据超时时间 FTPClient.setDataTimeout(10 * 60 * 10000); // socket连接,设置socket连接超时时间 FTPClient.setSoTimeout(10 * 60 * 100000); //2.登录服务器 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 FTPClient.login(userName, passWord); //3.判断登陆是否成功 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } FTPClient.setControlEncoding("UTF-8"); // 中文支持 FTPClient.setFileType(FTPClient.BINARY_FILE_TYPE); FTPClient.enterLocalPassiveMode(); //1.指定要下载的目录 FTPClient.changeWorkingDirectory(path);// 转移到FTP服务器目录 }catch (Exception e){ e.printStackTrace(); } } return FTPClient; } }
2.获取ftp服务器目录下的文件列表,并读取文件内容
读取方式1:
FTPClient ftp = FtpConnectUtil.getFtp(); try{ //1.遍历下载的目录 FTPFile[] fs = ftp.listFiles(); for (FTPFile ff : fs) { // 2.写操作,将其写入到本地文件中 File localFile = new File(localPath + ff.getName()); OutputStream is = new FileOutputStream(localFile); // 根据文件名读取其内容,并写入 ftp.retrieveFile(ff.getName(), is); is.close(); } }catch(Exception e){ }
读取方式2:
//遍历下载目录并循环 ****省略参考方式1****** // 每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据。 ftp.enterLocalPassiveMode(); // 从服务器上读取指定的文件内容。该方法容易报错 InputStream ins = ftp.retrieveFileStream(ff.getName()); if (ins != null) { ********对读取内容操作********** BufferedReader reader2 = new BufferedReader(new InputStreamReader(ins, "UTF-8")); String tempString = null; while ((tempString = reader.readLine()) != null) { tempString为ftp文件每行内容,其他操作此处省略。。。 } ********读完后********** reader.close(); ins.close(); //避免读取ins报空指针 ftp.completePendingCommand(); }
大数据量的读取请看下篇。。。
浙公网安备 33010602011771号