|
Often one of the first applets that new Java programmers want to write in their own work involves reading a file of some sort. This could be simple database info, e.g. a list or table of values and descriptions, in text format. We have learned to read image files and audio files from an applet but have not yet read a text file. This is fairly easy to do. However, keep in mind that the SecurityManager restricts access to only those files accessible from the location of the html and java files. Below we show the code to read a text file from an applet. Note that we use the URL class that is convenient for accessing web resources. This class provides various methods and fields, e.g. separate fields for the domain, path and file, that can be useful. In this case, it also provides a method to obtain file access through an InputStream. Then we can wrap this stream with an InputStreamReader to provide proper character handling. Finally, a BufferedReader is wrapped around the stream to provide buffering to smooth out the stream flow and also to get the readLine() method for grabbing a whole line at once and returning it in a string.
|
||||||||||||
|
|||||||||||||