Java Reference
In-Depth Information
}
}
}
This recipe is very similar to Recipe 3.1. However, in this recipe, you must specify a URL
and a file to save that URL to. For example, to download the Heaton Research logo, you would
use the following command:
DownloadBinary http://www.httprecipes.com/images/logo.gif
./logo.gif
The above arguments will download the image shown above to a file named logo.jpg .
The above command simply shows the abstract format to call this recipe. For exact informa-
tion on how to run this recipe refer to Appendix B, C, or D, depending on the operating
system you are using.
As mentioned, this recipe is very similar to Recipe 3.1. It even uses the same
downloadPage function as Recipe 3.1; however, an extra method is added named
saveBinaryPage . This method is shown here.
public void saveBinaryPage(String filename, String page) throws
IOException
As you can see, this method accepts a filename and a page . The specified page
content will be saved to the local file specified by filename . The variable, page, con-
tains the actual contents of the page, as returned by the downloadPage function.
Saving the string to a binary file is very easy. The following lines of code do this.
OutputStream os = new FileOutputStream(filename);
os.write(page.getBytes());
os.close();
It is very simple. The stream is opened to a disk file, the contents of the string are written
to the file, and the file is closed. This recipe could be applied to any real-world site where you
need to download images, or other binary files to disk.
In this recipe, you learned how to download a binary file. Binary files are exact copies
of what is downloaded from the URL. In the next recipe you will see how to download a text
file.
Recipe #3.5: Downloading a Text File
This recipe will download a web page to a text file. But why is a text file treated differ-
ently than a binary file? They are treated differently because different operating systems end
lines differently. Table 3.2 summarizes how the different operating systems store text file line
breaks.
Search WWH ::




Custom Search