Java 如何将xml数据从URL保存到文件?

Java 如何将xml数据从URL保存到文件?,java,xml,Java,Xml,我想做的是获取此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

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


谢谢大家的帮助。

文件可能已经写完了

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


文件可能写得太多了

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


由于您已经在使用apaches commons io,您也可以简单地使用

FileUtils.copyURLToFile(URL, File)

请参见

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

FileUtils.copyURLToFile(URL, File)