java I/O流FileInputStream和FileReader使用及乱码问题

java I/O流FileInputStream和FileReader使用及乱码问题

使用FileInputStream和FileReader进行文件的读写,方式都是使用read(buf[])的方式,然后通过while循环进行输出。需要注意的是,FileInputStream读的是字节数组byte[],而FileReader读的是字符数组char[]。这也就是在构造String对象式出现不同的方式的原因。对于byte[]数组,如果不存在中文,那么直接使用
public String(byte[] bytes,
              int offset,
              int length)
这个构造函数就可以,但是如果有中文,需要给出以何种方式进行构造-->
public String(byte[] bytes,
              int offset,
              int length,
              Charset charset)
而相对于字符数组来说,就不要进行这样的转换,因为读取的时候,直接按照字符进行读取。这也就是代码中把从流中读到的数组转换成String对象时使用的方法不同的原因。
下面是代码:

package com.xueyoucto.xueyou;

import java.io.*;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) throws IOException{
        System.out.println("Hello World!");
        FileInputStream fileInputStream = new FileInputStream("d:/123.txt");
        byte[] bbuf = new byte[1024];
        int hasRead = 0;
        StringBuffer sb = new StringBuffer("");
        while((hasRead = fileInputStream.read(bbuf)) != -1){
            sb.append(new String(bbuf, 0, hasRead, "utf-8"));
        }
        fileInputStream.close();
        System.out.println(sb);

        System.out.println("");
        System.out.println("============================================================");
        FileReader fileReader = new FileReader("d:/123.txt");
        char cbuff[] = new char[1024];
        int cHasRead = 0;
        sb.setLength(0);
        while((cHasRead = fileReader.read(cbuff)) != -1){
            sb.append(cbuff,0,cHasRead);
        }
        fileReader.close();
        System.out.println(sb);
    }
}



运行效果:

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值