📜  Java IO-OutputStreamWriter(1)

📅  最后修改于: 2023-12-03 14:42:14.657000             🧑  作者: Mango

Java IO-OutputStreamWriter

Introduction

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.

Constructors

Here are some important constructors of the OutputStreamWriter class:

  1. OutputStreamWriter(OutputStream out): Creates an instance that uses the default character encoding scheme.
  2. OutputStreamWriter(OutputStream out, String charsetName): Creates an instance that uses the specified character encoding scheme.
  3. OutputStreamWriter(OutputStream out, Charset charset): Creates an instance that uses the specified character encoding scheme.
Important Methods

The OutputStreamWriter class provides various methods to write character-based data to the output stream. Some of the important methods include:

  1. void write(String str): Writes a string of characters to the output stream.
  2. void flush(): Flushes the output stream, ensuring that all buffered characters are written to the output stream.
  3. void close(): Closes the output stream.
Example Usage

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());
        }
    }
}
Conclusion

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.