A Practical File IO Example: The java.util.Properties Class


Sequential Character Stream File I/O Using Readers & Writers

The Reader and Writer classes support character-based file I/O more robustly than do their InputStream and OutputStream counterparts. The primary reason for this is their support for specifying the character set encoding scheme used to translate bytes or characters from the local file encoding to that required for the application. If you have a need to perform character-based file I/O then look to the Reader and Writer classes for your I/O solution.

As you can tell from looking at the inheritance hierarchy shown in figure 18-1 there are notably fewer Reader and Writer classes then there are InputStream and OutputStream classes. This is because Readers and Writers focus on character input and output. However, as you see the Readers and Writers put to use in this section, you will notice that for each Reader and Writer there is a corresponding InputStream and OutputStream class that performs a somewhat similar function. Chronologically during the evolution of the Java Platform API the InputStream and OutputStream classes appeared first followed by the Readers and Writers. It is their support for internationalization that makes Readers and Writers the preferred choice for providing character-based file I/O functionality.

Writers

In this section I will demonstrate the use of the FileWriter, BufferedWriter, and PrintWriter class. If you understood the material presented earlier about the OutputStream classes you can make a deadly accurate guess as to the intended purpose of a FileWriter, BufferedWriter, and PrintWriter. You’ll use a FileWriter to create a file to write characters to and a BufferedWriter to improve output efficiency by buffering the writes. The PrintWriter works a lot like the PrintStream class and allows you to write textual representations of Java primitive types and objects.

FileWriter

The FileWriter class has only five methods and they are all constructors. Its functionality derives from its base class OutputStreamWriter. When you create an object of type FileWriter it automatically creates an internal FileOutputStream object that it uses to write bytes to a file.

The FileWriter class is an exception to the flexible internationalization capability provided by Writer classes in general. When using a FileWriter class you are limited to writing characters to the default local encoding. If you need to specify an encoding other than the default you must use an OutputStreamWriter in conjunction with a FileOutputStream class.

Example 18.13 shows the FileWriter class in action.

Example 18.13: FWTesterApp.java

image from book
 1     import java.io.*; 2 3     public class FWTesterApp { 4       public static void  main(String[] args){ 5         try{ 6             FileWriter fw = new FileWriter("test.txt"); 7             fw.write("This is a test of the FileWriter class.\n"); 8             fw.write("It inherits its functionality from OutputStreamWriter.\n"); 9             fw.write("You can overwrite the contents of a file...\n"); 10            fw.write("...or you can append text to the end of a file."); 11            fw.close(); 12           }catch(Exception ignored){ } 13      } // end main 14    } // end class
image from book

Referring to example 18.13 — the FileWriter class stands pretty much on its own. To use it you simply create an object of type FileWriter, specifying the name of the file in the form of either a String or File reference, and you’re ready to write text to a file. The write() methods are provided by the FileWriter’s superclass OutputStreamWriter. Notice how, if you want to write lines of text, you have to manually insert the newline character ‘\n’. Figure 18-18 shows the contents of the text.txt file as viewed with a text editor after running this program.

image from book
Figure 18-18: Contents of test.txt File After Example 18.13 Executes

BufferedWriter

The BufferedWriter class provides output buffering for other Writer objects. It is used mostly in conjunction with a FileWriter or OutputStreamWriter object. Example 18.14 shows the BufferedWriter class in action.

Example 18.14: BWTesterApp.java

image from book
 1     import java.io.*; 2 3     public class BWTesterApp { 4       public static void  main(String[] args){ 5         try{ 6             FileWriter fw = new FileWriter("test.txt"); 7             BufferedWriter bw = new BufferedWriter(fw); 8             bw.write("This is a test of the BufferedWriter class."); 9             bw.newLine(); 10            bw.write("It improves output efficiency by buffering individual disk writes."); 11            bw.newLine(); 12            bw.write("You can specify the internal buffer size at the time of object creation."); 13            bw.newLine(); 14            bw.write("...and it provides a newLine() method!"); 15            bw.flush(); 16            bw.close(); 17           }catch(Exception ignored){ } 18      } // end main 19    } // end class
image from book

Referring to example 18.14 — the FileWriter object is created first and is used to create the BufferedWriter object. You can specify the size of its internal buffer via a constructor although in this example the default buffer size is utilized. The BufferedWriter object also provides a newLine() method. Figure 18-19 shows the contents of the image from book test.txt file as viewed with a text editor after this program executes.

image from book
Figure 18-19: Contents of test.txt After Example 18.14 Executes

OutputStreamWriter

The OutputStreamWriter provides character encoding flexibility. To use this class you must first create an OutputStream object. In this example a FileOutputStream will be used since we are writing to files.

If you need to provide output buffering you can use an OutputStreamWriter in conjunction with a BufferedWriter. Example 18.15 shows the OutputStreamWriter in action.

Example 18.15: OSWTesterApp.java

image from book
 1     import java.io.*; 2 3     public class OSWTesterApp { 4       public static void  main(String[] args){ 5         try{ 6             FileOutputStream fos = new FileOutputStream("test.txt"); 7             OutputStreamWriter osw = new OutputStreamWriter(fos); 8             BufferedWriter bw = new BufferedWriter(osw); 9             bw.write("Ohhhh do you love Java like I love Java?"); 10            bw.newLine(); 11            bw.write("The OutputStreamWriter needs a FileOutputStream object..."); 12            bw.newLine(); 13            bw.write("...and can be used with a BufferedWriter to improve output efficiency."); 14            bw.newLine(); 15            bw.write("...and it's fun to use!"); 16            bw.flush(); 17            bw.close(); 18           }catch(Exception ignored){ } 19      } // end main 20    } // end class
image from book

Referring to example 18.15 — the OutputStreamWriter needs to work with a FileOutputStream object in order to do its job. It can also be combined, as it is in this example, with a BufferedWriter to improve output efficiency. Figure 18-20 shows the contents of the image from book test.txt file as viewed with a text editor.

image from book
Figure 18-20: Contents of test.txt File After Example 18.15 Executes

PrintWriter

The PrintWriter class provides functionality similar to that of the PrintStream class in that it is used to write textual representations of Java primitive types and objects, as well as Strings and chars, to disk or other output destination. The PrintWriter must be used in conjunction with either an OutputStream object such as a FileOutputStream or a Writer object such as an OutputStreamWriter. When used with an OutputStreamWriter you can specify the desired character encoding. Example 18.16 shows the PrintWriter class in action.

Example 18.16: PWTesterApp.java

image from book
 1     import java.io.*; 2 3     public class PWTesterApp { 4       public static void main(String[] args){ 5         try{ 6             FileOutputStream fos = new FileOutputStream("test.txt"); 7             OutputStreamWriter osw = new OutputStreamWriter(fos); 8             BufferedWriter bw = new BufferedWriter(osw); 9             PrintWriter pw = new PrintWriter(bw); 10            pw.println(123);                                         // print integer literal 11            pw.println(true);                                        // print boolean literal 12            pw.println(1.234);                                       // print double literal 13            pw.println("Ohhhh I love Java!!");                       // print String literal 14            pw.println(new Person("Rick", "W", "Miller", "Male"));   // print Object String representation 15            pw.flush(); 16            pw.close(); 17           }catch(Exception ignored){ } 18      } // end main 19    } // end class
image from book

Referring to example 18.16 — The PrintWriter class is being used with a BufferedWriter to write character representations of Java primitive types and objects. In this example, the Person class is used to create a Person object on line 14. Figure 18-21 shows the contents of the image from book test.txt file as viewed with a text editor after example 18.16 executes.

image from book
Figure 18-21: Contents of test.txt File After Example 18.16 Executes

Readers

Reader classes are used to read characters from files or other character stream sources. Readers allow you to specify the character encoding used to translate the bytes read from the data source.

FileReader

The FileReader class reads bytes from a file and translates them according to the default local encoding. If you need more control over the encoding scheme use the InputStreamReader class directly. Example 18.17 shows the FileReader class in action.

Example 18.17: FRTesterApp.java

image from book
 1     import java.io.*; 2 3     public class FRTesterApp { 4       public static void main(String[] args){ 5        try{ 6            File file = new File("test.txt"); 7            FileReader fr = new FileReader(file); 8            char[] char_buffer = new char[(int)file.length()]; 9            fr.read(char_buffer); 10 11           for(int i = 0; i<char_buffer.length; i++){ 12             System.out.print(char_buffer[i]); 13           } 14           fr.close(); 15          }catch(Exception ignored){ } 16      } // end main 17    } // end class
image from book

Referring to example 18.17 — A File object is created on line 6 and is used to create the FileReader object on line 7. The File object is then used to get the length of the image from book test.txt file and use that value (cast to an integer) to create a character array named char_buffer. The char_buffer reference is then supplied as an argument to the read() method on line 9 where the entire contents of the image from book test.txt file is read into the char_buffer array. The for statement on line 11 iterates over the char_buffer array and prints each character to the console. Figure 18-22 shows the results of running this program.

image from book
Figure 18-22: Results of Running Example 18.17

InputStreamReader

The InputStreamReader class can be used when you need more control over the encoding scheme used to translate the bytes read from a file into characters. The InputStreamReader requires the services of an InputStream object to help it do its job. Example 18.18 uses an InputStreamReader in conjunction with a FileInputStream. Figure 18-23 shows the results of running this program.

Example 18.18: ISRTesterApp.java

image from book
 1     import java.io.*; 2 3     public class ISRTesterApp { 4       public static void main(String[] args){ 5        try{ 6            File file = new File("test.txt"); 7            FileInputStream fis = new FileInputStream(file); 8            InputStreamReader isr = new InputStreamReader(fis); 9            char[] char_buffer = new char[(int)file.length()]; 10           isr.read(char_buffer); 11 12           for(int i = 0; i<char_buffer.length; i++){ 13             System.out.print(char_buffer[i]); 14           } 15 16           isr.close(); 17          }catch(Exception ignored){ } 18      } // end main 19    } // end class
image from book

image from book
Figure 18-23: Results of Running Example 18.18

BufferedReader

The InputStreamReader can be used in conjunction with a BufferedReader to improve input efficiency. The size of the BufferedReader’s internal buffer can be specified at the time of instantiation. Example 18.19 shows a BufferedReader in action.

Example 18.19: BRTesterApp.java

image from book
 1     import java.io.*; 2 3     public class BRTesterApp { 4       public static void main(String[] args){ 5        try{ 6            File file = new File("test.txt"); 7            FileInputStream fis = new FileInputStream(file); 8            InputStreamReader isr = new InputStreamReader(fis); 9            BufferedReader br = new BufferedReader(isr); 10           char[] char_buffer = new char[(int)file.length()]; 11           br.read(char_buffer); 12 13           for(int i = 0; i<char_buffer.length; i++){ 14             System.out.print(char_buffer[i]); 15           } 16 17           br.close(); 18          }catch(Exception ignored){ } 19      } // end main 20    } // end class
image from book

Referring to example 18.19 — the BufferedReader object is created on line 9 using the InputStreamReader reference as an argument to its constructor. Figure 18-24 shows the results of running this program.

image from book
Figure 18-24: Results of Running Example 18.19

Quick Review

The Writer and Reader classes enable you to write and read character-oriented stream data to and from a file. If you need more control over the character encoding used in your program use the Reader and Writer classes for your file I/O operations.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net