Latest web development tutorials

Java FileWriter class

FileWriter class from OutputStreamReader class inherited. Such data is written to the stream by character. You can create objects needed through the following constructor.

Constructs a FileWriter object given a File object.

FileWriter(File file)

Constructs a FileWriter object given a File object.

 FileWriter(File file, boolean append)

Construct a file descriptor associated with FileWriter object.

FileWriter(FileDescriptor fd)

Construction FileWriter object given a file name, indicating whether it has a pending write data boolean value.

FileWriter(String fileName, boolean append)

After creating FileWriter object, you can refer to the following list of file operation method.

No. Method Description
1 public void write (int c) throws IOException
Write a single character c.
2 public void write (char [] c , int offset, int len)
Writes the character array to begin to offset a portion of a length of len.
3 public void write (String s, int offset, int len)
Write the string began to offset a portion of a length of len.

Examples

import java.io.*;
public class FileRead{
   public static void main(String args[])throws IOException{
      File file = new File("Hello1.txt");
      // 创建文件
      file.createNewFile();
      // creates a FileWriter Object
      FileWriter writer = new FileWriter(file); 
      // 向文件写入内容
      writer.write("This\n is\n an\n example\n"); 
      writer.flush();
      writer.close();
      //创建 FileReader 对象
      FileReader fr = new FileReader(file); 
      char [] a = new char[50];
      fr.read(a); // 从数组中读取内容
      for(char c : a)
          System.out.print(c); // 一个个打印字符
      fr.close();
   }
}

The above examples compiled results are as follows:

This
is
an
example