gpt4 book ai didi

java - 如何将 URL 中的 xml 数据保存到文件中?

转载 作者:行者123 更新时间:2023-12-01 21:47:48 25 4
gpt4 key购买 nike

我想要做的是获取此 URL 的内容:

https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=CYQB&hoursBeforeNow=2

并将其复制到文件中,以便我可以解析它并使用元素。

这是我到目前为止所拥有的:

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吗?

谢谢大家的帮助。

最佳答案

文件可能被覆盖。

您应该使用“追加”mode获取附加数据的文件(来自 readLine)。

public static void writeStringToFile(File file,
String data,
boolean append)

关于java - 如何将 URL 中的 xml 数据保存到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35738703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com