Writer、Reader

版权声明:ssupdding https://blog.csdn.net/sspudding/article/details/88718167

一、Writer(字符输出流)

1.操作步骤
  • 打开字符写操作流
  • 写操作
  • 关闭写操作流
    (三个步骤都会抛出IOException异常)
    public static void writer(){
        String path = "C:\\Users\\lo\\Desktop\\ss.txt";
        try {

            //构造函数
             /* public FileWriter(String fileName) throws IOException {
                    super(new FileOutputStream(fileName));
                }*/
           
            //打开字符写操作流
            FileWriter writer = new FileWriter(path,true);

            //构造函数  默认false, true是在文件尾追加,false直接覆盖原内容的形式写入
            /*public FileWriter(String fileName, boolean append) throws IOException {
                super(new FileOutputStream(fileName, append));
            }*/

            //写操作
            /*//void write(int c)  写入单个字符
            writer.write(97);

            //关闭
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
2.常用方法研究
void write(int c): 写入单个字符

void write(char cbuf[]):批量的写入字符,数据写入类型是char类型的

void write(char cbuf[], int off, int len):批量写的写入字符数组的某一部分,自定义起始和长度

void write(String str):直接写入字符串

write(String str, int off, int len): 直接写入字符串,自定义写入字符串子集

 Writer	append(char c) :将指定字符添加到此 writer,(追加数据的流必须和前期写入的流是同一个打开的流实例)(构造函数时append参数设置为true起作用)

abstract  void	flush() : 刷新该流的缓冲

abstract  void	close() :关闭此流,但要先刷新它

二、Reader(字符输入流)

读操作的步骤和上面的都一样啦,所以就研究一下它常用的方法就好了

int read(): 每次读取一个字符,返回值就是字符对应的ASCII码的数字

int read(char cbuf[]):批量读取数据,数据读取到char []数组中,返回值表示读取有效数据个数

int read(char cbuf[], int offset, int length):批量读取数据,数据读取到char []数组中,可以指定读取数据的起始和大小,返回值表示读取有效数据个数

上述读操作结束后都会返回-1
在这里插入图片描述
在这里插入图片描述

小练习:

实现文件的复制粘贴过程

public class Demo1 {


    public static void main(String[] args) throws IOException {

        String path = "C:\\Users\\lo\\Desktop\\ss.txt";

        //打开读写流
        FileInputStream input = new FileInputStream(path);
        FileOutputStream output = new FileOutputStream("C:\\Users\\lo\\Desktop\\a.txt");

        int byt = 0;

        //方法一
        while ((byt =input.read()) != -1) {
            output.write(byt);
        }

        /*//方法二
        byte[] bytes = new byte[10];
        while ((byt = input.read()) != -1){
            output.write(bytes,0,byt);
        }*/

        //关闭读写流
        input.close();
        output.close();
    }
 }

猜你喜欢

转载自blog.csdn.net/sspudding/article/details/88718167