Character-oriented output streams are subclasses of the Writer class, and their class hierarchy is shown in the figure.
The following table lists the main subclasses and descriptions of Writer.
Write files using FileWriter class
The FileWriter class is a subclass of the Writer subclass OutputStreamWriter class, so the FileWriter class can use both the Writer class methods and the OutputStreamWriter class methods to create objects.
When writing to a file using the FileWriter class, you must first call the FileWriter() constructor to create an object of the FileWriter class, and then call the writer() method. The format of the FileWriter constructor is:
public FileWriter(String name); //Create a writable output stream object based on the file name public FileWriter(String name,Boolean a); //a is true, the data will be appended behind the file
[Example] Use FileWriter class to write ASCⅡ characters to a file
import java.io.*;class ep10_3{ public static void main(String args[]){ try{ FileWriter a=new FileWriter("ep10_3.txt"); for(int i=32;i<126 ;i++){ a.write(i); } a.close(); } catch(IOException e){} }} After running the program, open the ep10_3.txt file and the content is displayed as:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_`abcdefghijklmnopqrstuvwxyz{|}
Write files using the BufferedWriter class
The BufferedWriter class is used to write data to a buffer. When using it, you must create a FileWriter class object, and then use this object as a parameter to create an object of the BufferedWriter class. Finally, you need to use the flush() method to clear the buffer. The BufferedWriter class has two constructors, and its format is:
public BufferedWriter(Writer out); //Create a buffer character output stream public BufferedWriter(Writer out,int size); //Create an output stream and set the buffer size
[Example] Use the BufferedWriter class to copy files
import java.io.*;class ep10_4{ public static void main(String args[]){ String str=new String(); try{ BufferedReader in=new BufferedReader(new F ileReader("ep10_4_a.txt")); BufferedWriter out =new BufferedWriter(new FileWriter("ep10_4_b.txt")); while((str=in.readLine())!=null){ System.out.println(str); out.write(str); //Replace 1 line of data read is written to the output stream out.newLine(); //Write to line breaks} out.flush(); in.close(); out.close(); } catch(IOException e){ System .out.println("Error occurred"+e); } }}It should be noted that when calling the write() method of the out object to write data, it will not be written to enter. Therefore, it is necessary to use the newLine() method to add a carriage return after each line of data to ensure that the target file is consistent with the source file. .