Java FileWriter class

Introduction

FileWriter creates a Writer to write to a file.

Four commonly used constructors are shown here:

FileWriter(String filePath )  
FileWriter(String filePath , boolean append)  
FileWriter(File fileObj )  
FileWriter(File fileObj , boolean append) 

import java.io.FileWriter;
import java.io.IOException;

public class Main {
   public static void main(String args[]) throws IOException {
      String source = "demo from demo2s.com\n" + " test\n" + " test.";
      char buffer[] = new char[source.length()];
      source.getChars(0, source.length(), buffer, 0);

      try (FileWriter f0 = new FileWriter("file1.txt");
            FileWriter f1 = new FileWriter("file2.txt");
            FileWriter f2 = new FileWriter("file3.txt")) {
         // write to first file
         for (int i = 0; i < buffer.length; i += 2) {
            f0.write(buffer[i]);//from   ww  w  .jav  a2s.c  om
         }

         // write to second file
         f1.write(buffer);

         // write to third file
         f2.write(buffer, buffer.length - buffer.length / 4, buffer.length / 4);

      } catch (IOException e) {
         System.out.println("An I/O Error Occured");
      }
   }
}



PreviousNext

Related