Java IO流 踩坑

在下面这个案例中,原来我是将输出流和输入流都放在最后关闭,但是读取的结果一直打印不出来,就调换了位置,输出流使用完之后就关闭,结果正确打印,记录一下。 

package Test;

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("1.txt"));
        osw.write("你好");
        osw.close();
        
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\hpuzjh\\Desktop\\hang\\1.txt"));
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = bis.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }
        bis.close();
    }
}

字节流读取中文字符,但是要保存文件还是要使用转换流和字符流,这里只是打印文件中的内容,所以可以调用String的构造方法进行。

发布了369 篇原创文章 · 获赞 74 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_41333844/article/details/103202600