java IO流FileInputStream和FileReader使用及乱码问题

    xiaoxiao2022-06-22  26

    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); } } 运行效果:
    转载请注明原文地址: https://ju.6miu.com/read-1122665.html

    最新回复(0)