【问题标题】:How to save xml data from a URL to a file?如何将 xml 数据从 URL 保存到文件?
【发布时间】:2016-03-02 04:45:09
【问题描述】:

我想做的是获取这个 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?

谢谢大家的帮助。

【问题讨论】:

    标签: java xml


    【解决方案1】:

    文件可能被覆盖了。

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

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

    【讨论】:

      【解决方案2】:

      因为你已经在使用 apaches commons-io,你也可以简单地使用

      FileUtils.copyURLToFile(URL, File)
      

      https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#copyURLToFile(java.net.URL,%20java.io.File)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-23
        • 2016-09-29
        • 1970-01-01
        相关资源
        最近更新 更多