Erik Price
Posts: 39
Nickname: erikprice
Registered: Mar, 2003
|
|
Re: Read from file
|
Posted: May 2, 2003 10:01 AM
|
|
There's actually a pretty significant difference between the two approaches.
Note that the first approach (your own approach) is to open up a FileReader and wrap it into a BufferedReader, and then read through the file in the normal fashion. This is a fine approach for reading the contents of a file in the system's filesystem.
The second approach is very different. First of all, it does not use the system's filesystem at all -- note how it calls getResourceAsStream, passing it a path-like argument. But although this may look like a filesystem path, it doesn't have to be. Take a look at the JavaDoc for java.lang.Class.getResourceAsProperties and you'll see that it is a also way to get to a resource that is tucked away within a JAR or WAR file -- in which case the the resource isn't a file.
There is yet another difference in the second approach. Note the use of the java.util.Properties class. This is not the same as opening up a file and reading it either. While a Properties object can be built from a properties file, it can also be built from a properties resource that is not a file (such as one that is located in a JAR or WAR). This is one of the handier Java classes, because once you've created a Properties object in this fashion (handing it a properties file or properties resource with the load method), it does the work of parsing the file for you. You don't have to come up with a syntax parser to look for name-value pairs, then separate them, then store them. You can just call getProperties on the Properties object and pass in the String name of the property whose value you are searching for.
Usually when you simply want to store key/value pairs like this in a file (or a non-file resource in a JAR/WAR), using a properties file is the easiest way to do it. It's fully supported by Java, and many other languages provide a means to read a properties file. And if you had to directly parse the file, it's not very complicated (though there are more ways to write it than just "name=value"). I recommend you read the java.util.Properties JavaDoc, it'll explain everything.
Note that there is a new class called java.util.Preferences which works similar to Properties, but isn't quite as easy to use (but is somewhat more flexible).
|
|