这里FTP上传使用的是:
commons-net:commons-net:3.6
首先登录
FTPClient client = new FTPClient();// 连接FPT服务器,设置IP及端口client.connect(host地址, port端口);client.login(userName用户名, passWord密码);client.changeWorkingDirectory(filePath文件夹名字);//设置上传模式client.setFileType(FTP.BINARY_FILE_TYPE);//是否开启被动模式client.setRemoteVerificationEnabled(false);client.enterLocalPassiveMode();//设置utf-8编码client.setControlEncoding("utf-8");
开始上传
File file = new File("本地文件路径");if (file.exists()) {//是否是文件夹if (file.isDirectory()) {//返回某个目录下所有文件和目录的绝对路径,返回类型File[]File[] children = file.listFiles();for (final File f : children) {File uploadFile = new File("路径"+ f.getName());FileInputStream srcFileStream = null;try {srcFileStream = new FileInputStream(uploadFile);} catch (FileNotFoundException e) {e.printStackTrace(); }boolean b = false;try {client.setCopyStreamListener(new MyUploadListener());//上传文件b = client.storeFile(上传目标文件夹 + "/" + 文件名称, srcFileStream);if (b) {("上传成功")srcFileStream.close();} else {srcFileStream.close();("上传失败");}} catch (IOException e) {e.printStackTrace();}}}}
上传监听:
class MyUploadListener implements CopyStreamListener{@Overridepublic void bytesTransferred(CopyStreamEvent event) {}@Overridepublic void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {("上传中:"+totalBytesTransferred+" byte")}}
现在是FTP下载:
使用的是ftp4j-1.7.2.jar
首先登录:
FTPClient client = new FTPClient(); // 连接FPT服务器,设置IP及端口client.connect(host路径, port端口);client.login(userName用户名, password密码);client.changeDirectory(filePath进入文件夹);
开始下载:
for (String fileName : 下载服务器文件夹) {Log.e(TAG, "进入log循环");if (!(fileName == null || fileName.isEmpty())) {//获取文件夹里所有文件try {loginClient.download(fileName, new File("下载文件夹地址" + fileName), new MyTest1Listener());} catch (IOException e) {e.printStackTrace();} catch (FTPIllegalReplyException e) {e.printStackTrace();} catch (FTPException e) {e.printStackTrace();} catch (FTPDataTransferException e) {e.printStackTrace();} catch (FTPAbortedException e) {e.printStackTrace();}} }
下载监听:
class MyTest1Listener implements FTPDataTransferListener {long downSize = 0;@Overridepublic void aborted() {("开始下载")}@Overridepublic void completed() {("下载完成")}@Overridepublic void failed() {("下载失败")}@Overridepublic void started() {// TODO Auto-generated method stub("下载开始")}@Overridepublic void transferred(int arg0) {// TODO Auto-generated method stubdownSize += arg0;("文件下载中:" + downSize + "byte")} }