OutputStreamWriter(OutputStream, String): This method is available in the java.io.OutputStreamWriter class of Java.
Syntax:
java.io.OutputStreamWriter.OutputStreamWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException
This method takes two arguments. This method creates an OutputStreamWriter that uses the named charset.
Parameters: Two parameters are required for this method.
out: An OutputStream.
charsetName: The name of a supported charset.
Throws:
1. UnsupportedEncodingException - If the named encoding is not supported
Approach 1: When no exception
Java
import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;public class OutputStreamWriterOutputStreamWriter4 {public static void main(String[] args) throws IOException {OutputStream out = new FileOutputStream("D:\\hello.txt");String charsetName = "UTF-8";OutputStreamWriter outputStreamWriter =new OutputStreamWriter(out, charsetName);System.out.println(outputStreamWriter);outputStreamWriter.close();}}
Output:
java.io.OutputStreamWriter@26f0a63f
Approach 2: UnsupportedEncodingException
Java
package com.OutputStreamWriter;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;public class OutputStreamWriterOutputStreamWriter4 {public static void main(String[] args) throws IOException {OutputStream out = new FileOutputStream("D:\\hello.txt");String charsetName = "UTF-899999";OutputStreamWriter outputStreamWriter =new OutputStreamWriter(out, charsetName);System.out.println(outputStreamWriter);outputStreamWriter.close();}}
Output:
Exception in thread "main" java.io.UnsupportedEncodingException: UTF-899999 at java.base/sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:67) at java.base/java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:99) at com.OutputStreamWriter.OutputStreamWriterOutputStreamWriter4.main(OutputStreamWriterOutputStreamWriter4.java:13)
Some other methods of OutputStreamWriter
close(): This method closes the stream, flushing it first.
flush(): This method flushes the stream.
getEncoding(): This method returns the name of the character encoding being used by this stream.
OutputStreamWriter(OutputStream): This method creates an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter(OutputStream, Charset): This method creates an OutputStreamWriter that uses the given charset.
OutputStreamWriter(OutputStream, CharsetEncoder): This method creates an OutputStreamWriter that uses the given charset encoder.
OutputStreamWriter(OutputStream, String): This method creates an OutputStreamWriter that uses the named charset.
write(int): This method writes a single character.
write(char[], int, int): This method writes a portion of an array of characters.
write(String, int, int): This method writes a portion of a string.
No comments:
Post a Comment