OutputStreamWriter class
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
OutputStreamWriter(OutputStream out)
- Creates an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter(OutputStream out, Charset cs)
- Creates an OutputStreamWriter that uses the given charset.
OutputStreamWriter(OutputStream out, CharsetEncoder enc)
- Creates an OutputStreamWriter that uses the given charset encoder.
OutputStreamWriter(OutputStream out, String charsetName)
- Creates an OutputStreamWriter that uses the named charset.
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.
Revised from Open JDK source code
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class Main {
public static void main(String[] args) throws Exception {
try {
FileOutputStream fos = new FileOutputStream("test.txt");
Writer out = new OutputStreamWriter(fos, "UTF8");
out.write("java2s.com");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}