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

标签 java xml

我想要做的是获取此 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/

相关文章:

java - 如何模拟 super 方法调用

java - 双指缩放仅放大到中心

xml - 用dart构建xml文档

json - 在 elasticsearch 中索引平面 XML 文件

xml - 使用 XSLT 转换 XML

java - 使用 Xerces 忽略奇怪的解析错误

java - 应用程序自动在宽度和高度上增加 10 个像素

java - 在特定的开始、结束日期和时间限制内运行 Quartz Scheduler Job

java - 如何从 XSD 生成带有 Bean Validation 注释的 Java 对象?

Java:使用 splitText() 方法分割节点