Re: Get a file from the web using java
"Allan M. Bruce" <allanmb@TAKEAWAYdsl.pipex.com> wrote in message
news:VLidneaCy5nJudPZnZ2dnUVZ8qidnZ2d@pipex.net...
I want to be able to get a file from the web from my java program and read
the contents. How can I do this?
For example, I want to get http://www.somewhere.com/file.txt so that I can
read the contents.
My previous answer was bothering me - I was almost certain there was an easy
way to read a file line by line but I couldn't think of it - so I did a
quick Google and confirmed that there is indeed a way to do that. I like
this approach a lot better than the one I suggested earlier:
/* Get the URL for the image file. */
URL textFileUrl = null;
try {
textFileUrl = new URL("http://www.somewhere.com/file.txt");
} catch (MalformedURLException excp) {
//error handling
}
/* Open an input stream on the URL. Open the readers that will read
the stream. */
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
inputStream = textFileUrl.openStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
} catch (IOException io_excp) {
//error handling
}
/* Read the file, one line at a time, and display the contents. */
try {
String inputLine = null;
while ((inputLine = bufferedReader.readLine()) != null) {
System.out.println(inputLine);
}
} catch (IOException io_excp) {
//error handling
}
/* Close the stream and the readers. */
try {
inputStream.close();
inputStreamReader.close();
bufferedReader.close();
} catch (IOException io_excp) {
//error handling
}
Mind you, I'm assuming you _want_ to deal with the text in the file as
lines. If you actually want to read primitives like ints and chars from the
text file, then the previous answer will probably be the way you want to go!
By the way, as an added 'bonus', this code will work with URLs other than
standard 'http://' URLs. You could specify the URL in any of these ways and
still read the file:
/* A standalone text file that is online. */
textFileUrl = new URL("http://www.somewhere.com/file.txt");
/* A text file found in a jar in the filesystem. */
textFileUrl = new
URL("jar:file:d:\\downloads\\test.jar!/META-INF/MANIFEST.MF");
/* A text file that is in a jar that is online. */
textFileUrl = new
URL("jar:http://my.com/jars/test.jar!/META-INF/MANIFEST.MF");
/* A text file that is in the local filesystem. */
textFileUrl = new URL("file:C:\\junk\\test.txt");
--
Rhino