Flo
Flo

Reputation: 7

How do I create a XML File from an URL

For a project I need to parse a XML file. The parsing in itself works with a File but I need to retrieve the file from an URL. How do I save the information from the URL to a file?

I already tried many of the answers provided here but since now none worked the way I would like them to. One of the answer I tried was the following:

public File createFile(URL url){
    File f;
    try {
      f = new File(url.toURI());
    } catch(URISyntaxException e) {
      f = new File(url.getPath());
    }
    return f;
}

Sadly this does not solve the problem but rather tells me that "URI scheme is not "file""

If anyone could help me with my problem I would be very thankful.

Upvotes: 0

Views: 2271

Answers (2)

qdoot
qdoot

Reputation: 131

Using Java IO, this will save it to a target.xml file:

public File createFile(URL url) throws IOException {

    File f = new File("C:\\Users\\my-user\\Desktop\\target.xml");

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

    OutputStream outStream = new FileOutputStream(f);
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        outStream.write(inputLine.getBytes());
    }

    outStream.close();
    in.close();

    return f;
}

Upvotes: 0

nortontgueno
nortontgueno

Reputation: 2821

I recommend you to use the Apache Commons IO library to fetch the content of your URL, you can do it with just one line:

IOUtils.toString(new URL("YOUR_URL_IN_HERE"), "UTF-8");

This will transform the content of your URL into a String, you can then write the content to a file or handle the content in any other stream you want.

Here you can find the docs of IOUtils

Upvotes: 1

Related Questions