java中文件字符流和缓冲流

本文介绍了Java中的字节流(如`FileInputStream`和`BufferedInputStream`)与字符流(如`FileReader`和`BufferedReader`)的特点,以及它们在复制文件和文本文件操作中的使用。重点讲解了如何正确处理字符流的缓冲和数据写入问题,以及字符缓冲流(如`BufferedWriter`)的新增功能。
摘要由CSDN通过智能技术生成

字节流:适合复制文件,不适合读写文本文件

字符流:适合读写文本文件

FileReader(文件字符输入流)

作用:把文件中的数据以字符的形式读入到内存中

public FileReader(File file) throws FileNotFoundException

Creates a new FileReader, given the File to read, using the default charset.

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader, given the name of the file to read, using the default charset

public int read() throws IOException 

每次读取一个字符返回,没有字符返回-1

public int read(char[] cbuf) throws IOException

每次用一个字符数组去读取数据,返回字符数组读取了多少个字符,如果没有数据可读返回-1

每次读取一个字符 

public class test1 {
    public static void main(String[] args) {
        try (
                Reader reader = new FileReader("day17-file-app\\src\\hhh.txt");
        ) {
            int c;
            while((c=reader.read())!=-1)
            {
                System.out.print((char)c);//循环读字符
            }

        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}

每次读一个字符数组 

public class test2 {
    public static void main(String[] args) {
        try (
                Reader reader = new FileReader("day17-file-app\\src\\hhh.txt");
        ) {
            char []buf=new char[3];
            int len;
            while((len=reader.read(buf))!=-1)//每次读取多个字符
            {
                System.out.println(new String(buf,0,len));//创建String类对象的时候,把buf的len个长度的字符清除
            }

        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}

 文件字符输出流(FileWriter):把内容写到文件

public FileWriter(File file) throws IOException

Constructs a FileWriter given the File to write, using the default charset

 public FileWriter(File file, boolean append) throws IOException

Constructs a FileWriter given the File to write and a boolean indicating whether to append the data written, using the default charset.

public FileWriter(String fileName) throws IOException

Constructs a FileWriter given a file name, using the default charset 

public FileWriter(String fileName, boolean append) throws IOException

Constructs a FileWriter given a file name and a boolean indicating whether to append the data written, using the default charset

 public void write(int c) throws IOException

写一个字符

public void write(char[] cbuf, int off, int len) throws IOException

写字符数组的一部分 

public void write(String str, int off, int len) throws IOException

写字符串的一部分 

public class test {
    public static void main(String[] args) {
        try (
                Writer writer = new FileWriter("day17-file-app/src/hhh3.txt");
                // Writer writer = new FileWriter("day17-file-app/src/hhh3.txt",true);//追加
                Reader reader=new FileReader("day17-file-app/src/hhh3.txt")
        )//会自己创建文件)
        {
            //1;写一个字符
            writer.write('a');
            //2:写一个字符串
            writer.write("你好hhh");
            String s="你好hhh";
            //3:写字符串的一部分
            writer.write(s,0,2);
            //4:写字符数组
            char []chars=new char[]{'1','我'};
            writer.write(chars);

            //换行
            writer.write("\n");
            writer.write("a");
//读取
            char []buf=new char[3];
            int len;
            //System.out.println(1);
            while((len=reader.read(buf))!=-1)//每次读取多个字符
            {
                System.out.println(new String(buf,0,len));//创建String类对象的时候,把buf的len个长度的字符清除
            }
            System.out.println(len);//-1:没有数据可读
           
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

可以发现len==-1,表明读不到数据 

 原因:字符流输出数据后,只是输出到缓冲区中,并没有写到文件,必须刷新流,或者关闭流,写出去的数据才有效

解决方法:调用flush()方法,刷新流之后,数据就会从缓冲区写到文件

写完数据后写:

writer.flush();

关闭流包括刷新流

 字节缓冲流:提高读写数据的性能


public BufferedInputStream(InputStream in)

Creates a BufferedInputStream and saves its argument, the input stream in, for later use. An internal buffer array is created and stored in buf.

 public BufferedOutputStream(OutputStream out)

Creates a new buffered output stream to write data to the specified underlying output stream.

public class test1 {
            public static void main(String[] args) {
                try (
                        InputStream in = new FileInputStream("day17-file-app\\src\\hhh.txt");
                        //封装成字节缓冲流
                        InputStream bin=new BufferedInputStream(in);
                        OutputStream out = new FileOutputStream("day17-file-app\\src\\Copyhhh1.txt", true);//追加写
                        OutputStream bout=new BufferedOutputStream(out);
                ) //把用到的资源都写在try的括号内,使用完会自动释放资源
                {
                    byte[] b = new byte[64];
                    int len;
                    while ((len = bin.read(b)) != -1) {
                        bout.write(b);//写数据
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }

 字符缓冲输入流(BufferedReader)

public BufferedReader(Reader in)

Creates a buffering character-input stream that uses a default-sized input buffer.

新加的功能

public String readLine() throws IOException

读取一行数据返回,没有数据返回null 

public class test2 {
    public static void main(String[] args) {
        try(
                Reader reader=new FileReader("day17-file-app\\src\\hhh.txt");
                //封装成字符缓冲输入流
                BufferedReader breader=new BufferedReader(reader);//因为要使用BufferReader新加的方法,就不使用多态
                ){
            /*int len;
            char []buf=new char[3];
            while((len=breader.read(buf))!=-1)
            {
                System.out.println(new String(buf,0,len));
            }*/
            String line;
            while((line=breader.readLine())!=null)
            {
                System.out.println(line);
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

 字符缓冲输出流(BufferedWriter)

public BufferedWriter(Writer out)

Creates a buffered character-output stream that uses a default-sized output buffer.

新增方法:
public void newLine() throws IOException

换行 

public class test3 {
    public static void main(String[] args) {
        try(
                Writer writer=new FileWriter("day17-file-app\\src\\hhh3.txt");
                //封装成字符缓冲输出流
                BufferedWriter bufferedWriter=new BufferedWriter(writer);

                Reader reader=new FileReader("day17-file-app\\src\\hhh3.txt");
                BufferedReader bufferedReader=new BufferedReader(reader);
                ){
            bufferedWriter.write('c');
            bufferedWriter.write("你好");
            bufferedWriter.newLine();
            bufferedWriter.write("h哈哈");
            bufferedWriter.flush();

            //读取
            String s;
            while((s=bufferedReader.readLine())!=null)
            {
                System.out.println(s);
            }
            /*c你好
              h哈哈*/

        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

 案例:

2.你好哈哈哈哈
3.helloworld
1.hhhhhhh
5.nnnnnnn
4.xxxxxxxx

把该文本按前面序号排序写到其他文件

public class test4 {
    public static void main(String[] args) {
        try(
                BufferedReader bufferedReader=new BufferedReader(new FileReader("day17-file-app\\src\\hhh3.txt"));
                BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter("day17-file-app\\src\\hhh4.txt"));
                )
        {
            //创建一个ArrayList集合存储每行数据
            ArrayList<String> list=new ArrayList<>();

            //开始读数据
            String line;
            while((line=bufferedReader.readLine())!=null)
            {
                //把数据添加到list中
                list.add(line);
            }

            //排序
            Collections.sort(list);//默认按首字母的ASCII码值升序,字符串比较可以使用ompareTo()方法

            //写数据
            for (String s : list) {
                bufferedWriter.write(s);
                bufferedWriter.newLine();
            }


        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

 

  • 13
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落落落sss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值