Yan Lamothe
Yan Lamothe

Reputation: 65

How to save xml data from a URL to a file?

What I wanna do is get the content of this URL :

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

and copy it to a file so I can parse it and use the elements.

Here is what I have so far :

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) {

        }

    }

}
}

The problem is that the content of s does not show up in input.txt.

If I replace s by any other strings it works. So I guess it's a problem with the data of s. Is it because it's xml?

Thank you all for the help.

Upvotes: 0

Views: 1357

Answers (2)

Jayan
Jayan

Reputation: 18459

The file is probably getting over-written.

You should use "append" mode to get file appended with data(from readLine).

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

Upvotes: 3

Emerson Cod
Emerson Cod

Reputation: 2090

as you are already using apaches commons-io, you can also simply use

FileUtils.copyURLToFile(URL, File)

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

Upvotes: 0

Related Questions