javaIO-字符流-OutputStreamWriter

本文详细介绍了OutputStreamWriter类的基本概念和使用方法,包括如何通过该类将字符数据写入输出流,并探讨了其内部实现机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

erOutputStreamWriter 是操作字符输出的一个类,用于写数据。
OutputStreamWriter 继承了Writer类。它有一个私有StreamEncoder 类型的常量属性 se,用于存储编码格式,会在对象初始化的时候指定,如果不指定,会调用系统平台默认的编码格式。如果在构造方法中传递了该参数,而实际上该参数的值是null或者“”,会抛出NullPointerException异常。查看编码格式可以调用writer.getEncoding()方法 返回OutputStreamWriter 类中属性se的值,一个string类型的。
void write(int c) 它是线程安全的,一个字符一个字符的去写
void write(char cbuf[], int off, int len)
void write(String str, int off, int len)
void write(String str) 这个方法在OutputStreamWriter 没有被重写,而是到它的父类中掉别的方法来实现。
在这些写方法的内部是使用StreamEncoder的write()方法的,具体的看下OutputStreamWriter 的写方法源码,如下。

    /**
     * Writes a single character.
     *
     * @exception  IOException  If an I/O error occurs
     */
    public void write(int c) throws IOException {
        se.write(c);
    }
    /**
     * Writes a portion of an array of characters.
     *
     * @param  cbuf  Buffer of characters
     * @param  off   Offset from which to start writing characters
     * @param  len   Number of characters to write
     *
     * @exception  IOException  If an I/O error occurs
     */
    public void write(char cbuf[], int off, int len) throws IOException {
        se.write(cbuf, off, len);
    }
    /**
     * Writes a portion of a string.
     *
     * @param  str  A String
     * @param  off  Offset from which to start writing characters
     * @param  len  Number of characters to write
     *
     * @exception  IOException  If an I/O error occurs
     */
    public void write(String str, int off, int len) throws IOException {
        se.write(str, off, len);
    }

而在Writer类中的void write(int c)方法是线程安全的。它在方法体中对属性 lock 进行 synchronized。

    /**
     * Writes a single character.  The character to be written is contained in
     * the 16 low-order bits of the given integer value; the 16 high-order bits
     * are ignored.
     *
     * <p> Subclasses that intend to support efficient single-character output
     * should override this method.
     *
     * @param  c
     *         int specifying a character to be written
     *
     * @throws  IOException
     *          If an I/O error occurs
     */
    public void write(int c) throws IOException {
        synchronized (lock) {
            if (writeBuffer == null){
                writeBuffer = new char[writeBufferSize];
            }
            writeBuffer[0] = (char) c;
            write(writeBuffer, 0, 1);
        }
    }

OutputStreamWriter基本信息说简单了介绍了些,下面使用该类网文件中写入数据。
实现思路:
声明File对象,不存在则去创建;
声明OutputStream对象,调用它的子类去创建对象 FileOutputStream。最为OutputStreamWriter构造函数的入参;
声明OutputStreamWriter 对象;
执行写方法;
关闭流,从后往前关闭,先关闭OutputStreamWriter 在关闭OutputStream。
附上代码,供参考。

package cmc.com.jer.cmc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class Demo6 {

    public static void main(String[] args) {

        File file = new  File("e://app/fw.txt");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        OutputStream out =null;
        OutputStreamWriter writer = null;
        try {
              out = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        writer = new OutputStreamWriter(out);
        String str ="test write method in class named OutputStreamWriter";
        try {
            System.out.println(writer.getEncoding());
            writer.write(str,0,str.length());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

查看本地问下会发现数据被写入到了文件中。现在有个问题,是否可以对原先的文件进行追加内容,似的原先的内容不会被覆盖掉。回答是否定的。因为 OutputStreamWriter 类中的构造方法,没有给出一个标识,怎么去写文件。要想实现在原文件的基础上追加内容,有两个方法。其一,使用字节流。其二,自己创建一个和OutputStreamWriter 类类似的字符串写入类,去覆盖和重写里面的方法。看到这里其实也发现OutputStreamWriter类存在的意义,它是作为字节和字符转换的一个桥梁,熟练使用好这个桥梁,操作IO会更简单、方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值