如何从java检查FTP服务器上的文件可写

时间:2014-02-20 20:40:43

标签: java ftp fileinputstream ftp-client

我能够连接Ftp服务器。我的要求是检查登录到服务器后显示的路径是否可以在ftp服务器中写入。 以下代码未检查File remotefile = new File(pwd)

public StringBuffer verifyMath(String host, String uname, String password, String cType){
    String MathString = "FTPHost:[" + host + "];uname[" + uname + "];cType[" + cType + "]";
    StringBuffer mBuffer = new StringBuffer();
    FileInputStream fis = null;
    FTPClient client = new FTPClient();

    try {
        client.connect(host);
        boolean login = client.login(uname, password);
        client.getReplyCode(); //230
        if (login == true) {
            log.debug("Connection established...");

            String pwd = client.printWorkingDirectory();
            File remotefile = new File(pwd);
            boolean rmtfile = remotefile.canWrite();
            boolean rmtdir = remotefile.isDirectory();

            if(!(remotefile.isDirectory() && remotefile.canWrite())) {
                mBuffer.append(MathLogger.raiseError(MathString, "Math is not Writable"));
            }           

            boolean logout = client.logout();
            if (logout) {
                log.debug("Connection close...");
            }
        } else {
            mBuffer.append(MathLogger.raiseError(MathString, "Connection failed."));
        }

    } catch (IOException e) {
        mBuffer.append(MathLogger.raiseError(MathString, e));
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return mBuffer;
}

1 个答案:

答案 0 :(得分:2)

mlistFile(或可能是mlistDir)可能是您要在远程目录上调用的API。这将返回具有权限信息的FTPFile对象。当然,这些仅在FTP服务器支持RFC 3659扩展名时才有效。

类似于:

FTPFile remoteDir = client.mlistFile(client.printWorkingDirectory());
if (remoteDir.hasPermission(FTPFile.USER_ACCESS,FTPFile.WRITE_PERMISSION)) {
  ...
}