Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Making the pieces fit together in Java (Document vs File)

  1. #1
    Junior Member
    Join Date
    Nov 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question 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:
    File f1 = new File("Readme.txt");
    		File f2 = new File("Output.txt");
     
    		InputStream in = new FileInputStream(f1);
    		OutputStream out = new FileOutputStream(f2);
     
    		byte[] buf = new byte[1024];
    		int len;
    		while (( len = in.read(buf)) > 0) {
    			out.write(buf, 0, len);
    		}
    		in.close();
    		out.close();
    And this makes an exact copy of the input file.

    The second like this:
    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.
    Last edited by TenLeftFingers; November 18th, 2012 at 02:10 PM. Reason: Summarised what code snippets are doing


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default 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.

  3. #3
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default 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.

  4. #4
    Junior Member
    Join Date
    Nov 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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.

  5. #5
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default 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.

  6. #6
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default 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.

    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.

  7. #7
    Junior Member
    Join Date
    Nov 2012
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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?

Similar Threads

  1. Conversion of any document file to wiki page.
    By vizz in forum Web Frameworks
    Replies: 3
    Last Post: November 6th, 2012, 01:59 PM
  2. Replies: 1
    Last Post: July 16th, 2011, 08:55 AM
  3. making a .bat file that compiles your java files
    By sp11k3t3ht3rd in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 24th, 2010, 12:55 AM
  4. JTable is not fit to the screen width.
    By rajakumarjk in forum AWT / Java Swing
    Replies: 2
    Last Post: October 12th, 2010, 10:13 AM
  5. Replies: 2
    Last Post: March 6th, 2009, 03:00 PM