项目上使用了apache commons net包,发现获取服务器上的文件的时间比真实时间少了8个小时,debug了一下午,原以为是时区的问题,但是最终发现似乎源码是有问题的。 主要是FTPTimestampParserImpl.java的parseTimestamp方法,代码如下:
/**
* Implements the one {@link FTPTimestampParser#parseTimestamp(String) method}
* in the {@link FTPTimestampParser FTPTimestampParser} interface
* according to this algorithm:
*
* If the recentDateFormat member has been defined, try to parse the
* supplied string with that. If that parse fails, or if the recentDateFormat
* member has not been defined, attempt to parse with the defaultDateFormat
* member. If that fails, throw a ParseException.
*
* This method allows a {@link Calendar} instance to be passed in which represents the
* current (system) time.
*
* @see org.apache.commons.net.ftp.parser.FTPTimestampParser#parseTimestamp(java.lang.String)
*
* @param timestampStr The timestamp to be parsed
*/
public Calendar parseTimestamp(String timestampStr) throws ParseException {
Calendar now = Calendar.getInstance();
return parseTimestamp(timestampStr, now);
}
这个方法的参数是一个时间字符串,是从服务器上返回的(类似于我们通过终端连接服务器 执行“ls -l”命令 看到的时间部分,只有年月时分)。方法的第一行,按照注释上的意思是服务器时间,但是实际上代码是在本地执行,获取的一定是本地时间,问题似乎就出现在这里,紧接着第二行调用了另外一个方法,代码如下:
public Calendar parseTimestamp(String timestampStr, Calendar serverTime) throws ParseException {
// 方法体就省略了,从参数名就可以看出来 第二个参数应该是服务器时间
}
注释太多,就不贴出来了,从参数名就可以看出来 第二个参数应该是服务器时间。