目录

FileWriter类(FileWriter Class)

此类继承自OutputStreamWriter类。 该类用于编写字符流。

该类有几个构造函数来创建所需的对象。 以下是一个清单。

Sr.No. 构造函数和描述
1

FileWriter(File file)

此构造函数在给定File对象的情况下创建FileWriter对象。

2

FileWriter(File file, boolean append)

此构造函数在给定File对象的情况下创建FileWriter对象,该对象具有指示是否附加写入数据的布尔值。

3

FileWriter(FileDescriptor fd)

此构造函数创建与给定文件描述符关联的FileWriter对象。

4

FileWriter(String fileName)

给定文件名,此构造函数创建FileWriter对象。

5

FileWriter(String fileName, boolean append)

此构造函数创建一个FileWriter对象,给定一个文件名,其中包含一个布尔值,指示是否附加写入的数据。

一旦掌握了FileWriter对象,就会有一个辅助方法列表,可用于操作文件。

Sr.No. 方法和描述
1

public void write(int c) throws IOException

写一个字符。

2

public void write(char [] c, int offset, int len)

写入从offset开始并且长度为len的字符数组的一部分。

3

public void write(String s, int offset, int len)

写一个String的一部分,从offset开始,长度为len。

例子 (Example)

以下是演示课程的示例 -

import java.io.*;
public class FileRead {
   public static void main(String args[])throws IOException {
      File file = new File("Hello1.txt");
      // creates the file
      file.createNewFile();
      // creates a FileWriter Object
      FileWriter writer = new FileWriter(file); 
      // Writes the content to the file
      writer.write("This\n is\n an\n example\n"); 
      writer.flush();
      writer.close();
      // Creates a FileReader Object
      FileReader fr = new FileReader(file); 
      char [] a = new char[50];
      fr.read(a);   // reads the content to the array
      for(char c : a)
         System.out.print(c);   // prints the characters one by one
      fr.close();
   }
}

这将产生以下结果 -

输出 (Output)

This
is
an
example
↑回到顶部↑
WIKI教程 @2018