Java - StringWriter flush() method



Description

The Java StringWriter flush() method flushes the stream.

Declaration

Following is the declaration for java.io.StringWriter.flush() method.

public void flush()

Parameters

NA

Return Value

This method does not return a value.

Exception

NA

Example - Usage of StringWriter flush() method

The following example shows the usage of StringWriter flush() method.

StringWriterDemo.java

package com.tutorialspoint;

import java.io.StringWriter;

public class StringWriterDemo {
   public static void main(String[] args) {

      // create a new writer
      StringWriter sw = new StringWriter();

      // create a new sequence
      String s = "Hello world";

      // write a string
      sw.write(s);

      // flush the writer
      sw.flush();

      // print result
      System.out.println("" + sw.toString());
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Hello World

Example - Using flush() after writing

The following example shows the usage of StringWriter flush() method.

StringWriterDemo.java

package com.tutorialspoint;

import java.io.StringWriter;

public class StringWriterDemo {
   public static void main(String[] args) {
      try {
         StringWriter sw = new StringWriter();
         sw.write("Buffered ");
         sw.write("content");

         sw.flush();  // Has no effect, but safe to call

         System.out.println("Output: " + sw.toString());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Output: Buffered content

Explanation

  • flush() is called after writing.

  • It does nothing, but the StringWriter continues to function normally.

Example - Repeated flushing

The following example shows the usage of StringWriter flush() method.

StringWriterDemo.java

package com.tutorialspoint;

import java.io.StringWriter;

public class StringWriterDemo {
   public static void main(String[] args) {
      try {
         StringWriter sw = new StringWriter();
         sw.write("Flush ");
         sw.flush();  // Does nothing
         sw.write("has ");
         sw.flush();  // Still does nothing
         sw.write("no effect.");

         System.out.println("Output: " + sw.toString());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Output: Flush has no effect.

Explanation

  • Multiple calls to flush() are made between writes.

  • All calls are harmless and do not affect the written content.

java_io_stringwriter.htm
Advertisements