Apache FTPClient调用listFiles(path)方法时包含中文路径问题

来源:互联网 发布:如何关掉淘宝客 编辑:程序博客网 时间:2024/06/01 12:18

最近使用Apache Commons Net下的FTPClient进行项目的开发,需要列出远程ftp某个目录下的文件,调用FTPClient的listFiles()方法。

在调用client.listFiles(String path)方法时,出现了对于指定路径,不能获取该路径下的子文件数组的情况。开始以为是path路径填写错误,试过多种路径方式,还是不能顺利获取到子文件数组。最后发现是路径中带有中文的问题,要进行寻址,需要对含有中文的路径进行转码。

使用如下代码进行转码,然后调用listFiles(path)方法:

String iso_path=new String(origin_path.getBytes("gb2312"),"iso-8859-1");//origin_path:带有中文的路径 iso_path:转码后的路径client.listFiles(iso_path);

至此问题就解决了。

附:

Apache Commons Net的API说明(Commons API 3.3):

public FTPFile[] listFiles(String pathname) throws IOException
Using the default system autodetect mechanism, obtain a list of file information for the current working directory or for just a single file.

This information is obtained through the LIST command. The contents of the returned array is determined by the FTPFileEntryParser used.

使用默认的系统自动检测机制,获得当前工作目录或一个但以文件下的文件列表信息。这些信息是通过LIST命令获取的。返回的数组内容是使用的FTPFileEntryParser决定的。

Parameters:
pathname - The file or directory to list. Since the server may or may not expand glob expressions, using them here is not recommended and may well cause this method to fail. Also, some servers treat a leading '-' as being an option. To avoid this interpretation, use an absolute pathname or prefix the pathname with ./ (unix style servers). Some servers may support "--" as meaning end of options, in which case "-- -xyz" should work.
pathname-路径名,需要列出文件信息的文件或目录。由于服务器可能不会拓展glob表达式,不推荐在在这里使用并且可能会导致方法调用失败。另外,一些服务器会将开头的‘-’符号认为是一个选项。为了避免这样的情况,使用一个绝对路径或者使用‘ ./ ’为前缀的路径(UINIX类的服务器)。一些服务器可能还支持“--”作为选项的结尾,例如“-- -xyz”应该就可以。
Returns:
The list of file information contained in the given path in the format determined by the autodetection mechanism
Throws:
FTPConnectionClosedException - If the FTP server prematurely closes the connection as a result of the client being idle or some other reason causing the server to send FTP reply code 421. This exception may be caught either as an IOException or independently as itself.
IOException - If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
ParserInitializationException - Thrown if the parserKey parameter cannot be resolved by the selected parser factory. In the DefaultFTPEntryParserFactory, this will happen when parserKey is neither the fully qualified class name of a class implementing the interface org.apache.commons.net.ftp.FTPFileEntryParser nor a string containing one of the recognized keys mapping to such a parser or if class loader security issues prevent its being loaded.
See Also:
DefaultFTPFileEntryParserFactoryFTPFileEntryParserFactoryFTPFileEntryParser

0 0