Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Write File



Write To File in Groovy

We can write to a file in Groovy using multiple ways. Following are three most popular ways to create a file in Groovy −

  • Using FileOutputStream() constructor

  • Using FileWriter.write() method

  • Using Files.write() method

Let's take a look at each of the way to write file in Groovy.

Write To File Using FileOutputStream Constructor

FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.

Syntax

Following constructor takes a file name as a string to create an output stream object to write the file −

OutputStream f = new FileOutputStream("hello.txt") 

Example - Write To File Using FileOutputStream Constructor

Following is the example to demonstrate FileOutputStream to write a file in current directory −

Example.groovy

class Example {
   public static void main(String[] args) {
      try {
         byte[] bytes = [65, 66, 67, 68, 69];
         OutputStream os = new FileOutputStream("test.txt");
         for(int x = 0; x < bytes.length ; x++) {
            os.write( bytes[x] );   // writes the bytes
         }
         os.close();
     
         InputStream is = new FileInputStream("test.txt");
         int size = is.available();

         for(int i = 0; i < size; i++) {
            System.out.print((char)is.read());
         }
         is.close();
      } catch (IOException e) {
         System.out.print("Exception");
      }	
   }
}

The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.

Output

ABCDE  

Write To File Using FileWriter.write() Method

FileWriter.write() method allows to write chars to a file as shown below −

Syntax

// get an existing file
File file = new File("test.txt");

// Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();

Example: Write To File Using FileWriter.write() Method

Following is the example to demonstrate File to write to a file in given directory using FileWriter.write() method −

class Example {
   static void main(String[] args) {
      try {
          File file = new File("test.txt");
          
          //Create the file
          if (file.createNewFile()) { 
             System.out.println("File is created!");
          } else {
             System.out.println("File already exists.");
          } 
          
          // Write Content
          FileWriter writer = new FileWriter(file);
          writer.write("Test data");
          writer.close();
          
          
          // read content
          FileReader reader = new FileReader(file);
          
          int c;
          while ((c = reader.read()) != -1) {
        	  char ch = (char) c;
              System.out.print(ch);
          }
      } catch (IOException e) {
         System.out.print("Exception");
      }	
   }
}

The above code would create file test.txt and would write given string in text format. Same would be the output on the stdout screen.

Output

File is created!
Test data

Write To File using withWriter Method

File object, can be created with a custom writer to write to a file as shown below−

Syntax

new File('test.txt').withWriter('utf-8') { writer -> writer.writeLine 'Hello World' }

Example: Write To File Using Files.write() Method

Following is the example to demonstrate to write a file in given directory using Files.write() method −

class Example {
   static void main(String[] args) {  
      try {
         new File('test.txt').withWriter('utf-8') { 
            writer -> writer.writeLine 'Hello World'
         }
      } catch (IOException e) {
         System.out.print("Exception");
      }	
   }
}

The above code would create file test.txt and would write given string in text format.

Output

Hello World
Advertisements