字符流中的编码解码问题,以及字符流写数据的5种方式

本文详细介绍了字符流在编码与解码过程中的注意事项,包括如何选择一致的编码格式,如GBK或UTF-8。并通过示例代码展示了五种字符流写数据的方法,以及如何读取并显示文件内容。

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

字符流中的编码与解码,格式得一样,选用相同的编码和解码格式。

字符流写数据的5种方式:

void write(int c) :写入一个字符;

void write(char[] chars):写入一个字符数组

void write(char[] chars, int off, int len):写入字符数组的一部分

void write(String str) :写入一个字符串

选用相同的编码和解码格式:GBK,默认UTF-8;代码如下,

void write(char[] chars, int off, int len)写入字符数组的一部分这种方式:

public class ConversionStreamDemo {
    public static void main(String[] args) {
        OutputStreamWriter osw = null;
        InputStreamReader isr = null;
        try {
            //写入a.txt文件
            osw = new OutputStreamWriter(new FileOutputStream("a.txt"),"GBK");
            osw.write("唐人盛世一条街");
            osw.flush();

            //读取a.txt文件,并输出到控制台
            isr = new InputStreamReader(new FileInputStream("a.txt"),"GBK");
            char[] chars = new char[1024];
            int len = 0;
            while ((len = isr.read(chars)) != -1){
                System.out.println(new String(chars,0,len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (osw != null && isr != null){
                try {
                    osw.close();
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值