【发布时间】:2016-03-02 04:45:09
【问题描述】:
我想做的是获取这个 URL 的内容:
并将其复制到一个文件中,以便我可以解析它并使用元素。
这是我目前所拥有的:
package test;
import java.io.*;
import java.net.*;
import org.apache.commons.io.FileUtils;
public class JavaGetUrl {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws FileNotFoundException {
URL u;
InputStream is = null;
DataInputStream dis;
String s = null;
try {
u = new URL(
"https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=CYQB&hoursBeforeNow=2");
is = u.openStream(); // throws an IOException
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null) {
System.out.println(s);
FileUtils.writeStringToFile(new File("input.txt"), s);
}
} catch (MalformedURLException mue) {
System.out.println("Ouch - a MalformedURLException happened.");
mue.printStackTrace();
System.exit(1);
} catch (IOException ioe) {
System.out.println("Oops- an IOException happened.");
ioe.printStackTrace();
System.exit(1);
} finally {
try {
is.close();
} catch (IOException ioe) {
}
}
}
}
问题是 s 的内容没有出现在 input.txt 中。
如果我将 s 替换为任何其他字符串,它就可以工作。所以我猜是s的数据有问题。是不是因为是xml?
谢谢大家的帮助。
【问题讨论】: