dsa

Java OutputStreamWriter

In this tutorial, we will learn about the Java OutputStreamWriter, its constructors and its methods with the help of an example.

An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may be given explicitly.

Constructors of OutputStreamWriter

Methods

MethodsDesciption
void close()Closes the stream, flushing it first.
void flush()Flushes the stream.
String getEncoding()Returns the name of the character encoding being used by this stream.
void write(char[] cbuf, int off, int len)Writes a portion of an array of characters.
void write(int c)Writes a single character.
void write(String str, int off, int len)Writes a portion of a string.

Examples :


import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class CodeMistic
{

  	public static void main(String args[]) 
	{

    		String data = "This file consists of a single line.";

    		try 
		{
      			// Creates a FileOutputStream
      			FileOutputStream file = new FileOutputStream("output.txt");

      			// Creates an OutputStreamWriter
      			OutputStreamWriter output1 = new OutputStreamWriter(file);

      			// Writes string to the file
      			output1.write(data);

      			// Creates an output stream reader specifying the encoding
      			OutputStreamWriter output2 = new OutputStreamWriter(file, Charset.forName("UTF8"));

      			// Returns the character encoding of the output stream
      			System.out.println("Character encoding of output1: " + output1.getEncoding());
      			System.out.println("Character encoding of output2: " + output2.getEncoding());

      			// Closes the reader
      			output1.close();
      			output2.close();
    		}
    		catch (Exception e) 
		{
      			e.getStackTrace();
    		}
  	}
}


//A file will be created named output.txt and it will contain the below line:
//This file consists of a single line.

Output :

The character encoding of output1: Cp1252
The character encoding of output2: UTF8