📅  最后修改于: 2023-12-03 14:42:14.657000             🧑  作者: Mango
In Java, the OutputStreamWriter
class is a class that bridges character streams to byte streams. It converts characters into bytes by using a specified character encoding. The OutputStreamWriter
is a useful tool for writing character-based data to byte-based output streams, such as file output streams or network output streams.
To use the OutputStreamWriter
, you need to create an instance of this class and provide an output stream object, along with the character encoding scheme to be used. This class provides several constructors to accomplish this.
Here are some important constructors of the OutputStreamWriter
class:
OutputStreamWriter(OutputStream out)
: Creates an instance that uses the default character encoding scheme.OutputStreamWriter(OutputStream out, String charsetName)
: Creates an instance that uses the specified character encoding scheme.OutputStreamWriter(OutputStream out, Charset charset)
: Creates an instance that uses the specified character encoding scheme.The OutputStreamWriter
class provides various methods to write character-based data to the output stream. Some of the important methods include:
void write(String str)
: Writes a string of characters to the output stream.void flush()
: Flushes the output stream, ensuring that all buffered characters are written to the output stream.void close()
: Closes the output stream.Here's an example that demonstrates the usage of OutputStreamWriter
to write to a file:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
String filename = "output.txt";
// Create an output stream
FileOutputStream fos = new FileOutputStream(filename);
// Create an instance of OutputStreamWriter using default character encoding
OutputStreamWriter writer = new OutputStreamWriter(fos);
// Write a string to the file
writer.write("Hello, world!");
// Flush and close the writer
writer.flush();
writer.close();
System.out.println("Data written to file successfully!");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
The OutputStreamWriter
class in Java provides a convenient way to write character-based data to byte-based output streams. By using this class, you can easily convert characters into bytes using different character encoding schemes. Make sure to close the OutputStreamWriter
once you are done writing data to the output stream.