字节,字符缓冲流读写数据(IO流)

1.字节缓冲流读写数据

import java.io.*;

//字节缓冲流读写数据
public class demo03 {
    public static void main(String[] args) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("test\bbb.txt"));
        bos.write(98); //write(int b)  写入一个字符 b
        bos.write(97); //write(int b)  写入一个字符 a
        bos.write("qweqwe".getBytes(),0,4);  //write(byte[] b,int off,int len) 写入字节数组索引0-4的的值
        bos.close();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("test\bbb.txt"));
        byte[] b = new byte[1024];
        int len =0;
        while((len=bis.read(b))!=-1){
            System.out.println(new String(b,0,len));//打印读的字节数组
        }
        //关闭字节缓冲流,释放空间
        bis.close();
     }
}

2.字符缓冲流读写数据

import java.io.*;

//字符缓冲流读写数据
public class demo04 {
    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("test\ccc.txt"));
        bw.write("rtyyhrtgeg",0,6); //write(String s,int off, int len)
        bw.write("
");
        char[] ch = new char[]{q,w,q};
        bw.write(ch,0,2); // write(char[] ch,int off, int len);
        bw.close();
        BufferedReader br = new BufferedReader(new FileReader("test\ccc.txt"));
        String line =null;
        while((line=br.readLine())!=null){ //读一行数据,不包括回车换行符
            System.out.println(line);
        }
        //关闭字符缓冲流,释放空间
        
        br.close();
    }
}
经验分享 程序员 微信小程序 职场和发展