0

我有一个带有 ListView 的活动。我正在使用 Apache FTP Commons 连接并使用文件和目录填充 ListView。如何确定所选项目是文件还是目录?

public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.ftp);

        editAddress = (EditText) findViewById(R.id.editAddress);
        editUser = (EditText) findViewById(R.id.editUsername);
        editPassword = (EditText) findViewById(R.id.editPassword);
        remote = (ListView) findViewById(R.id.localList);
        itla.setListItems(directoryEntries);
        remote.setAdapter(itla);

        remote.setOnItemClickListener(this);
        connect = (ToggleButton) findViewById(R.id.connectButton);
        connect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                address = editAddress.getText().toString();
                user = editUser.getText().toString();
                pass = editPassword.getText().toString();
                ftpConnect(address, user,pass, 21);
            }
        });

    }

    public boolean ftpConnect(String host, String username, String password,
            int port) {
        try {
            mFTPClient = new FTPClient();
            // connecting to the host
            mFTPClient.connect(host, port);

            // now check the reply code, if positive mean connection success
            if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
                // login using username & password
                boolean status = mFTPClient.login(username, password);

                /*
                 * Set File Transfer Mode
                 * 
                 * To avoid corruption issue you must specified a correct
                 * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
                 * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE for
                 * transferring text, image, and compressed files.
                 */
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                mFTPClient.enterLocalPassiveMode();

                ftpPrintFilesList(ftpGetCurrentWorkingDirectory());
                return status;
            }
        } catch (Exception e) {
            // Log.d(TAG, "Error: could not connect to host " + host );
        }

        return false;
    }

    public boolean ftpDisconnect() {
        try {
            mFTPClient.logout();
            mFTPClient.disconnect();
            return true;
        } catch (Exception e) {
            // Log.d(TAG,
            // "Error occurred while disconnecting from ftp server.");
        }

        return false;
    }

    public String ftpGetCurrentWorkingDirectory() {
        try {
            String workingDir = mFTPClient.printWorkingDirectory();
            return workingDir;
        } catch (Exception e) {
            // Log.d(TAG, "Error: could not get current working directory.");
        }

        return null;
    }

    public boolean ftpChangeDirectory(String directory_path) {
        try {
            return mFTPClient.changeWorkingDirectory(directory_path);
        } catch (Exception e) {
            // Log.d(TAG, "Error: could not change directory to " +
            // directory_path);
        }

        return false;
    }

    public void ftpPrintFilesList(String dir_path) {
        try {
            FTPFile[] ftpFiles = mFTPClient.listFiles(dir_path);
            int length = ftpFiles.length;

            for (int i = 0; i < length; i++) {
                File name = new File(ftpFiles[i].getName());
                boolean isFile = ftpFiles[i].isFile();
                boolean isDirectory = ftpFiles[i].isDirectory();
                if (isDirectory) {
                    Drawable currentIcon = getResources().getDrawable(
                            R.drawable.folder);
                    directoryEntries.add(new IconifiedText(name, currentIcon));

                    // Log.i(TAG, "File : " + name);
                } else if (isFile) {
                    Drawable currentIcon = getResources().getDrawable(
                            R.drawable.mimetxt);
                    directoryEntries.add(new IconifiedText(name, currentIcon));
                    // Log.i(TAG, "Directory : " + name);
                }
                Collections.sort(this.directoryEntries);
                itla.setListItems(directoryEntries);
                remote.setAdapter(itla);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int position,
            long id) {
        String selectedFile = directoryEntries.get(position).getText();
        try {
            ftpPrintFilesList(selectedFile);
            itla.notifyDataSetChanged();
        } catch (NullPointerException e) {

        }
        Toast.makeText(FTPConnector.this, selectedFile, Toast.LENGTH_LONG)
                .show();

    }
}

Toast 返回正确的文件名。

这是使用反斜杠建议的完整代码,供任何可能觉得有用的人使用。

public class FTPConnector extends Activity implements OnItemClickListener {

    public ListView remote;
    public ArrayAdapter<String> adapter;
    public FTPClient mFTPClient = null;
    public ToggleButton connect;
    public EditText editAddress;
    private String address;
    public String currentDirectory = "/";
    public EditText editUser;
    private String user;

    public EditText editPassword;
    private String pass;
    public File[] fileList;
    public HashMap<String, Boolean> map = new HashMap<String, Boolean>();

    private List<IconifiedText> directoryEntries = new ArrayList<IconifiedText>();
    private IconifiedTextListAdapter itla = new IconifiedTextListAdapter(this);
    public String[] files;

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.ftp);

        editAddress = (EditText) findViewById(R.id.editAddress);
        editUser = (EditText) findViewById(R.id.editUsername);
        editPassword = (EditText) findViewById(R.id.editPassword);
        remote = (ListView) findViewById(R.id.remoteList);
        itla.setListItems(directoryEntries);
        remote.setAdapter(itla);

        remote.setOnItemClickListener(this);
        connect = (ToggleButton) findViewById(R.id.connectButton);
        connect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    address = editAddress.getText().toString();
                    user = editUser.getText().toString();
                    pass = editPassword.getText().toString();
                    ftpConnect(address, user,
                            pass, 21);
                } else {
                    ftpDisconnect();
                    directoryEntries.clear();
                    itla.notifyDataSetChanged();
                }
            }
        });

    }

    public boolean ftpConnect(String host, String username, String password,
            int port) {
        try {
            mFTPClient = new FTPClient();
            // connecting to the host
            mFTPClient.connect(host, port);

            // now check the reply code, if positive mean connection success
            if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
                // login using username & password
                boolean status = mFTPClient.login(username, password);

                /*
                 * Set File Transfer Mode
                 * 
                 * To avoid corruption issue you must specified a correct
                 * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
                 * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE for
                 * transferring text, image, and compressed files.
                 */
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                mFTPClient.enterLocalPassiveMode();

                ftpPrintFilesList(ftpGetCurrentWorkingDirectory());
                return status;
            }
        } catch (Exception e) {
            // Log.d(TAG, "Error: could not connect to host " + host );
        }

        return false;
    }

    public boolean ftpDisconnect() {
        try {
            mFTPClient.logout();
            mFTPClient.disconnect();
            return true;
        } catch (Exception e) {
            // Log.d(TAG,
            // "Error occurred while disconnecting from ftp server.");
        }

        return false;
    }

    public String ftpGetCurrentWorkingDirectory() {
        try {
            String workingDir = mFTPClient.printWorkingDirectory();
            return workingDir;
        } catch (Exception e) {
            // Log.d(TAG, "Error: could not get current working directory.");
        }

        return null;
    }

    public boolean ftpChangeDirectory(String directory_path) {
        try {
            return mFTPClient.changeWorkingDirectory(directory_path);
        } catch (Exception e) {
            // Log.d(TAG, "Error: could not change directory to " +
            // directory_path);
        }

        return false;
    }

    public void ftpPrintFilesList(String dir_path) {
        map.clear();
        try {
            FTPFile[] ftpFiles = mFTPClient.listFiles(dir_path);
            int length = ftpFiles.length;

            for (int i = 0; i < length; i++) {
                File name = new File(ftpFiles[i].getName());
                boolean isFile = ftpFiles[i].isFile();
                boolean isDirectory = ftpFiles[i].isDirectory();
                if (isDirectory) {
                    Drawable currentIcon = getResources().getDrawable(
                            R.drawable.folder);
                    directoryEntries.add(new IconifiedText(name, currentIcon));
                    map.put(ftpFiles[i].getName(),
                            Boolean.valueOf(ftpFiles[i].isDirectory()));
                    // Log.i(TAG, "File : " + name);
                } else if (isFile) {
                    Drawable currentIcon = getResources().getDrawable(
                            R.drawable.mimetxt);
                    directoryEntries.add(new IconifiedText(name, currentIcon));
                    map.put(ftpFiles[i].getName(),
                            Boolean.valueOf(ftpFiles[i].isFile()));
                    // Log.i(TAG, "Directory : " + name);
                }
                Collections.sort(this.directoryEntries);
                itla.setListItems(directoryEntries);
                remote.setAdapter(itla);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int position,
            long id) {

        String selectedFile = directoryEntries.get(position).getText();
        boolean isDirectory = map.get(selectedFile).booleanValue();
        if (isDirectory) {
            directoryEntries.clear();
            itla.notifyDataSetChanged();
            ftpPrintFilesList(selectedFile);
        } else if (!isDirectory) {
            Toast.makeText(FTPConnector.this, selectedFile, Toast.LENGTH_LONG)
                    .show();
        }

    }
}
4

1 回答 1

2

当您使用FTPClientApache Commons Net 的 a 时,如果您列出一个目录,客户端将向您发送一个FTPFiles 数组。每个FTPFile都有一个isDirectory()andisFile()方法,可以告诉您它是目录还是文件。

Apache Commons FTP 文件 JavaDoc

所以你基本上需要在你的列表中找到哪个文件具有选定的名称(也许使用getName()函数在其中搜索?),然后使用FTPFile类中提供的两种方法之一

更新

尝试这个:

声明一个 HashMap 实例变量

//this will contain the file name and it's isDirectory() result
HashMap<String, Boolean> map = new HashMap<String, Boolean>();

现在,在ftpPrintFilesList(path)方法的开头:

//resets the map, you are listing new FTPFiles, so older ones need to be removed
map.clear(); 

然后,在您的for循环中,ftpPrintFilesList(path)将每个 FTPFile 信息添加到地图中,如下所示:

//Add file's name and isDirectory() value to the map
map.put(ftpFiles[i].getName(),new Boolean(ftpFiles[i].isDirectory()));

最后,在onItemClick方法中,只需使用

boolean isDirectory = map.get(selectedFile).booleanValue();

true如果选中的项目是目录,则返回,false如果是文件

于 2013-04-27T21:42:07.287 回答