This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes Reading data from url and then outputting as string? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reading data from url and then outputting as string?" Watch "Reading data from url and then outputting as string?" New topic
Author

Reading data from url and then outputting as string?

Jason Mill
Greenhorn

Joined: Jul 29, 2003
Posts: 6
I am opening a connection to a URL and I want to send the data read onto a browser. In this case I am reading a pdf file. It looks like the null characters in the pdf file are not being sent or being changed somehow and so subsequently the pdf file is empty. It works great for html/text files. Im using DataInputStream with read to get the url data and DataOuputStream.writeBytes to output the data. I have tried many other combinations. (BufferedInputStream, BufferedReader, OutputStreamWriter)
Am I missing something - how do I stop the file being corrupted, Can this be done?
Any help greatly appreciated.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

A PDF file doesn't contain a String, and trying to treat it as one is going to cause problems when Java converts to/from the internal Unicode representation of character data. While this will work OK for textual data like HTML, it will totally destroy a PDF file.
Don't wrap the InputStream you get from the URLConnection with anything -- just call read(byte[]) on it directly, and write the data using FileOutputStream.write(byte[]). This will result in an exact copy of what you read from the URL being put into your file, and your problem should go away.
The classic implementation would look something like this:


[Jess in Action][AskingGoodQuestions]
Brian Pipa
Ranch Hand

Joined: Sep 29, 2003
Posts: 299
I don't know exactly what you're trying to do, but why not just send the URL itself to the browser and let the browser handle it? You can do it easily with the BrowserLauncher class from http://browserlauncher.sourceforge.net
Brian
[ October 16, 2003: Message edited by: Brian Pipa ]

My Java Freeware:<br />MACCC - <a href="http://maccc.pipasoft.com" target="_blank" rel="nofollow">http://maccc.pipasoft.com</a><br />Nator - <a href="http://nator.pipasoft.com" target="_blank" rel="nofollow">http://nator.pipasoft.com</a>
Jason Mill
Greenhorn

Joined: Jul 29, 2003
Posts: 6
Thanks Ernest, that pointed me in the right driection. I'm in the process of converting from using strings.
 
 
subject: Reading data from url and then outputting as string?