public static boolean downloadFile(String ip, int port, String username,
String password, String remotePath, String fileName,
String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
// 下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
conf.setServerLanguageCode("zh");
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();

System.out.println("reply:"+reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();


for (int i = 0; i < fs.length; i++) {
FTPFile ff = fs[i];
if (!ff.getName().equals(".") && !ff.getName().equals("..")) { File localFile = new File(localPath + File.separator
+ ff.getName());

if(!localFile.exists())//如果文件已存在则不重复下载
{
OutputStream is = new FileOutputStream(localFile); // 注意此处retrieveFile的第一个参数由GBK转为ISO-8859-1编码。否则下载后的文件内容为空。
// 原因可能是由于aix系统默认的编码为ISO-8859-1
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),
"ISO-8859-1"), is);
is.close();
}
}
} SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

ftp.logout();
success = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
return success;
}
downloadFile("132.228.39.77", 21, "oa_user", "oa_user","/attachments", "", "");上面这段代码在我本地运行木有问题,可以获取到文件列表;但是放到服务器(Linux)上运行获取不到文件列表
请高手帮忙看看!
谢谢!

解决方案 »

  1.   

    程序应该没什么问题,主要是linux上存储介质是以斜杠/根目录开始的,你试用相对路径试一下。
      

  2.   


    看了看你的编程风格,问题可能出在: File.separatorWindows下你用File.separator 得到的是 \
    但在Linux下你用用File.separator 得到的是 /但你所访问的FTP服务器,可能只认识 \
    ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
    你先用System.out.println(remotePath); 看看输出的内容,是否跟Windows下的不一致?
      

  3.   

    不好意思,突然发现你的remotePath是写死的。另一个建议是:检查下ftp.changeWorkingDirectory(remotePath); 的返回值是不是 false?
      

  4.   

    如果你想让你写的这个程式通用,跨操作系统(最起码在Windows系列的和linux系统的都通用的话),路径的获取就不能写死了。判断操作系统os类型:
    //判斷os是windows還是linux  
                Properties prop = System.getProperties();  
                String os = prop.getProperty("os.name");  
                if(os.toLowerCase().indexOf("windows") != -1){//windows  
                    filePath= localPath + "\\"
                                + ff.getName();  
                }else if(os.toLowerCase().equals("linux")){//Linux  
                    filePath= localPath + "/"
                                + ff.getName();                                     
                }  
      

  5.   

    这个解决来么?我也有这个问题,我ftp链接到的也是Lunix系统,ftp.changeWorkingDirectory(remotePath)这个返回到是true,可是就是PICTURE:/root/.tencent/qq//AppData/file//sendpix2.jpg