Making the pieces fit together in Java (Document vs File)
Becoming a fluid programmer
I've just finished two java tutorials. The first one demonstrates a basic file copy operation, and the second shows how to read and display a remote file.
I tried to put the two together: to read a remote xml file and save it to the local hard drive. But the objects just aren't adding up. What about my approach is wrong here?
The first looks like this:
And this makes an exact copy of the input file.
The second like this:
Code java:
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("http://feeds.feedburner.com/d0od?format=xml");
NodeList list = doc.getElementsByTagName("title");
System.out.println("There are " + list.getLength() + " items.");
Displays the contents of the xml "title" nodes.
But when I retrieve the xml feed in the second example, it is a Document ultimately, and in the first example I need an InputStream and OutputStream object to complete the write to file. How do I put the two together?
I'm not only interested in a solution here, but what *approach* I should be taking. Despite understanding both examples, I am unable to implement something new from them and this is bothering me as it seems to be something fundamental to Java that I'm missing here.
Re: Making the pieces fit together in Java (Document vs File)
The two halves aren't meant to be put together! What I mean is the second one actually reads the xml data and figures out what the content means in some sense. (This is what the document builder stuff is doing). That's fine if you want to count items or whatever, but if you want to save the data to disk all you want to do is read the data then write it without anything resembling document building.
So the program you want will more resemble the first one. The input stream will be different - because you are getting something from the network - but the overall logic will be the same. Have a look at Reading Directly from a URL (The Java™ Tutorials > Custom Networking > Working with URLs)
They use a BufferedReader rather than an input stream, which makes sense since the xml file is a text file. Where they have System,out.println() you might want to create a FileWriter and use that to write the text.
Re: Making the pieces fit together in Java (Document vs File)
You're coming into this problem from two orthogonal approaches. Approach one is a byte-level streaming file input and output, a type of input and output that is valid for all file types, be they text, image, sound, ... whatever. The second approach is to take a text xml file and try to parse it into a DOM or Document Object Model, a logical construct which is pretty far removed from that of naked bytes held on a disk. To write the DOM to disk, you would need further XML tricks such as a Transformer that transforms the DOM to an output Stream.
Re: Making the pieces fit together in Java (Document vs File)
pbrockway2, thank you. When you say the BufferedReader makes sense for a text file, do you think the tutorial I followed that uses the InputStreams is a bad example? Also, how would I go about figuring that out myself? I looked at the methods and return types for the objects I had and couldn't find anything that matched.
curmudgeon, I understand what you're saying. I think my understanding of the objects I'm using is a bit shallow. You probably would agree with that. Any suggestions on how to improve? The java docs are a bit lacking in terms of contextual use. If I keep going through the core java library will the pieces fall in to place, so to speak?
Thank you both for responding.
Re: Making the pieces fit together in Java (Document vs File)
My recommendation would be to get a firmer grip on core Java before futzing with XML "magic", but perhaps that's just me, and it is the order with which I approached it. More recently when tasked with using XML, I usually opt for using JAXB which would involve reading an XML file and transforming it into objects, also known as "unmarshalling", and then the converse of transforming objects into an XML file, or "marshalling". But again, I would consider these more advanced Java topics than most of the basics and again would save approaching them until later.
Re: Making the pieces fit together in Java (Document vs File)
I agree with curmudeon - not only will dealing with the xml aspect of the data hurt your head, but it will not really help with what you're trying to do. The url delivers you a bunch of text and you want to write it to a file on your disk. There's no need to worry about the actual xml content.
Did you try the Oracle Tutorial example? Replace their url with your one and you should see the xml displayed on your console. Surrounding pages describe what it is doing.
The remaining piece is to write the lines of text to a file rather than print them to the console. The I/O Streams (The Java™ Tutorials > Essential Classes > Basic I/O) section is good for an overview of what streams are. It's a bit light on examples, but the "Buffered Streams" page gives an example of creating a BufferedWriter which will play the role of out in your code. BufferedWriter has methods that can replace the System.out.println() in the Tutorial reading a url example.
Code :
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
//URL oracle = new URL("http://www.oracle.com/");
URL url = new URL("http://feeds.feedburner.com/d0od?format=xml");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
//outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("feeds.xml"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
//System.out.println(inputLine);
/*
* Use methods from BufferedWriter to put the string - and the
* newline! - into out
*/
}
in.close();
out.close();
}
}
That's not tested or anything, but it's where I would start. Then deal with exceptions. I've left the lines from the two Tutorial examples in as comments so you can see where things come from, but they wouldn't be in your actual code.
Re: Making the pieces fit together in Java (Document vs File)
curmudgeon, I definitely prefer order when it comes to learning so I'll do that. Probably with a book on core java as I like the containment of a good authors selections.
pbrockway2, I did try the example, and it works a treat. I was put off by the new objects initially because whenever I look up a possible solution online the answer is always a new object and I thought I should be able to get it to work with the objects I know already :) Obviously I was wrong.
I graduated several years ago and want to start working (as a 'mature' graduate) but my god there seems to be a lot of objects to work with and I'm finding it difficult to get back into things. The DVD tutorial I'm using was very good but only covered the basics.
With respect to web tutorials, I prefer a tool that's fairly complete such as a good book that covers all of the Core Java topics that the author thinks are important. When I follow web tutorials, I never know if what I'm learning is really relevant or not. There seems to be a constant flow of new objects and the ones I learn pass by rarely to be seen again. Does it ever come full circle?