Wednesday

URLs to Local Files






The URL class can also be used to access files in the local file system. Thus the URL class can be a handy way to open a file, if you need your code to not know whether the file came from the network or local file system.

Here is an example of how to open a file in the local file system using the URL class: URL url = new URL("file:/c:/data/test.txt");

URLConnection urlConnection = url.openConnection();
InputStream input = urlConnection.getInputStream();

int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
input.close();


Notice how the only difference from accessing a file on a web server via HTTP is the the URL: "file:/c:/data/test.txt".

0 comments:

Post a Comment