请注意是文件夹的内容,不是文件。所用的包是sun.net.ftp.FtpClient!我需要明确的知道如何便利的到文件夹下的文件。问题解决分数可以再加!
我需要知道的是如何获取远程文件夹下的文件夹列表?
java FTPClient如何删除远程服务器端的文件夹及其子文件夹及其内容!
答案:2 悬赏:20
解决时间 2021-03-21 05:48
- 提问者网友:曖昧情执
- 2021-03-20 16:36
最佳答案
- 二级知识专家网友:24K纯糖
- 2021-03-20 17:35
//遍历文件
public List getFileList(FtpClient ftpClient, String serverPath,
String prefix, String suffix) throws Exception {
List list = new ArrayList();
DataInputStream dis = new DataInputStream(ftpClient
.nameList(serverPath));
String filename = "";
while ((filename = dis.readLine()) != null) {
list.add(filename);
}
return list;
}
//删文件
public void deleteFileFromFtp(FtpClient ftpClient, String delFileName,
String serverPath) throws Exception {
ftpClient.cd(serverPath);
ftpClient.sendServer("dele " + delFileName + "\r\n");
}
删文件夹的话就先遍历再删
文件夹列表用apache提供的ftp包可以,sun的没看过
public List getFileList(FtpClient ftpClient, String serverPath,
String prefix, String suffix) throws Exception {
List list = new ArrayList();
DataInputStream dis = new DataInputStream(ftpClient
.nameList(serverPath));
String filename = "";
while ((filename = dis.readLine()) != null) {
list.add(filename);
}
return list;
}
//删文件
public void deleteFileFromFtp(FtpClient ftpClient, String delFileName,
String serverPath) throws Exception {
ftpClient.cd(serverPath);
ftpClient.sendServer("dele " + delFileName + "\r\n");
}
删文件夹的话就先遍历再删
文件夹列表用apache提供的ftp包可以,sun的没看过
全部回答
- 1楼网友:萌萌哒小可爱
- 2021-03-20 17:45
楼上说了遍历文件夹底下所有文件的方法
ftpClient所带的API提供了
ftpClient.sendServer("DELE " + filename + "\r\n");
但是它没有返回值,所以在实际应用中它还是有时候存在删不掉的问题。
贴一段代码不知道是不是你想要的。
import sun.net.ftp.*;
import java.io.*;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Iterator;
import java.lang.*;
import java.text.DecimalFormat;
//FtpClass类
class FtpClass {
FtpClient client;
private String host;
private String username;
private String password;
private String path = "/";
private int port = 21;
private static FtpClass instance;
private FtpClass() {
}
// 获得唯一实例
public static FtpClass getInstance() {
if (instance == null) {
instance = new FtpClass();
}
return instance;
}
// 连接FTP,并进入当前的path
public void connect() throws IOException {
if (client == null) {
client = new FtpClient(host, port);
client.login(username, password);
client.binary();
client.cd(path);
}
else {
client.noop();
client.cd(path);
}
}
// 关闭FTP
public void close() throws IOException {
if (client != null) {
client.closeServer();
client=null;
}
}
// 获得FTPClient类,可以直接对其操作
public FtpClient getClient() throws IOException {
if (client == null) {
connect();
}
return client;
}
// 返回当前目录的所有文件及文件夹
public ArrayList getFileList() throws IOException {
BufferedReader dr = new BufferedReader(new InputStreamReader(client.list()));
ArrayList al = new ArrayList();
String s = "";
while ( (s = dr.readLine()) != null) {
if ((
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯