我有一个包含属性的文件,其中指定了NOAA网站的URL,该网站包含一个温度数据集。该属性包含一个[DATE_REPLACE]
标记,因为每天当NOAA生成新的预测时,URL会更改。
在我的属性文件中,我正在指定:
WEATHER_DATA_URL="http://weather.noaa.gov/pub/SL.us008001/DF.anf/DC.mos/DS.mex/RD.[DATE_REPLACE]/cy.00.txt"
我已经在 PropertyHelper
类中声明了一个方法(它是 java.util.Properties
的包装器),用于生成当前日期的 URL 字符串,使用 WEATHER_DATA_URL
作为名称,"yyyyMMdd" 作为日期格式,以今天的日期作为参数。
public String getPropertyWithDateReplaceToken(String name, String dateFormat, Date dateToFormat)
{
String value = this.properties.getProperty(name);
if (StringHelper.isNullOrWhitespace(value) || !value.contains("[DATE_REPLACE]"))
{
throw new UnsupportedOperationException("The property value should specify the [DATE_REPLACE] token");
}
StringBuilder sb = new StringBuilder(value);
int index = sb.indexOf("[DATE_REPLACE]");
while (index != -1)
{
String replacement = StringHelper.getTodayAsDateString(dateFormat, dateToFormat);
sb.replace(index, index + "[DATE_REPLACE]".length(), replacement);
index += replacement.length();
index = sb.indexOf(value, index);
}
return sb.toString();
}
我随后调用另一个帮助类的以下方法来从网页中读取文本:
public static List<String> readLinesFromWebPage(String urlText) throws Exception
{
List<String> lines = new ArrayList<String>();
if (StringHelper.isNullOrWhitespace(urlText))
{
throw new NullPointerException("URL text cannot be null or empty");
}
BufferedReader dataReader = null;
try
{
System.out.println("URL = " + urlText);
String trimmedUrlText = urlText.replaceAll("\\s", "");
URL url = new URL(trimmedUrlText);
dataReader = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while((inputLine = dataReader.readLine()) != null)
{
lines.add(inputLine);
}
return lines;
}
catch(Exception e)
{
logger.logThrow(Level.SEVERE, e, "Exception (" + e.getMessage() + ") attempting to " +
"read data from URL (" + urlText + ")");
throw e;
}
}
正如您所看到的,我已经尝试从生成的URL字符串中修剪空格,希望这可以解决问题。URL字符串已经正确生成,但是我遇到了以下异常:
java.net.MalformedURLException: no protocol: "http://weather.noaa.gov/pub/SL.us008001/DF.anf/DC.mos/DS.mex/RD.20121219/cy.00.txt"
如果我手动设置字符串,一切都正常……我错过了什么吗?