JAVA 读写文件(InputStream,FileReader)什么是输入流/输出流?

47 篇文章 0 订阅

目录

什么是输入输出流

字节流

说明

inputstream   outputstream

使用总结:

方法总结:

 FileOutputStream   FileInputStream

字符流

说明

FileReader         FileWriter

缓冲流

说明

读取文件

复制文件(包含了写入文件) 

性能比较


什么是输入输出流

输入流的话 就是将数据从各种输入设备(包括文件、键盘等)中读取到内存中,

输出流则正好相反,是将数据从内存中的数据写入到各种输出设备(比如文件、显示器、磁盘等)。

哈哈,是不是和你想的不一样那?不是问题记住就行了,加油&&

字节流

说明

适用于所有的场景,也是最原始的读写操作

inputstream   outputstream

输出流                输入流(覆盖/追加)

import java.io.*;
import java.nio.charset.StandardCharsets; 

public static void FileReadWrite() {
        String path = "F:\\a.txt";
        //新建一个文件对象
        File file = new File(path);
        //文件读取
        try {
            //创建输入流((以内存为参照物)从文件输入到内存中叫输入流,相反为输出流),用于读取文件
//如果你这里有疑惑看总结            
InputStream inputStream = new FileInputStream(file);
            //定义一个字节数组
            byte[] b = new byte[1024];
            //将文件读入b,如果读完后b数组没有满,则b的剩余位置用空格填充
            inputStream.read(b);
            //新建字符串对象,并指定编码方式
            String res = new String(b, StandardCharsets.UTF_8);
            //.trim()方法用于去除多余的空格
            System.out.println(res.trim());

            inputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        

        String path2 = "F://b.txt";
        File file2 = new File(path2);
        //写入
        //输出流(从内存输入到文件中)
        OutputStream out = null;
        try {
            //新建输出流对象
            //注意这里的FileOutputStream的弟2个参数为true时表示追加,反之为覆盖
            out = new FileOutputStream(file2, true);
            //写入文件的字符串
            String inputString = "测试一下爱";
            //以字节的方式写入
            out.write(inputString.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //记得最终的释放
        finally {
            if (out != null) {
                try {
                    out.close();
                }
                catch (Exception e)
                {
                    System.out.println(e.getMessage());
                }
            }
        }

使用总结:

1 inputstream类和outputstream类都为抽象类,不能创建对象,可以通过子类来实例化。

2 inputstream类和outputstream类是输入输出字节用的类

3 里面的各个方法都有可能会产生异常,记得try,catch包裹,或者使用断言

方法总结:

inputstream

public abstract int read( ):
读取一个byte的数据,返回值是高位补0的int类型值。

public int read(byte b[ ]):
读取b.length个字节的数据放到b数组中。返回值是读取的字节数。该方法实上是调用下一个方法实现的

public int read(byte b[ ], int off, int len):
从输入流中最多读取len个字节的数据,存放到偏移量为off的b数组中。

public int available( ):
返回输入流中可以读取的字节数。注意:若输入阻塞,当前线程将被挂起,如果InputStream对象调用这个方法的话,它只会返回0,这个方法必须由继承InputStream类的子类对象调用才有用,

public long skip(long n):
忽略输入流中的n个字节,返回值是实际忽略的字节数, 跳过一些字节来读取

public int close( ) :
我们在使用完后,必须对我们打开的流进行关闭.

OutputStream

public void write(byte b[ ]):
将参数b中的字节写到输出流。

public void write(byte b[ ], int off, int len) :
将参数b的从偏移量off开始的len个字节写到输出流。

public abstract void write(int b) :
先将int转换为byte类型,把低字节写入到输出流中。

public void flush() : 
将数据缓冲区中数据全部输出,并清空缓冲区。

public void close() : 
关闭输出流并释放与流相关的系统资源。

 FileOutputStream   FileInputStream

    public static void FileOutput_InputStream()
    {
        String Path="F://a.txt";
        //输出流
        try {
            FileInputStream input=new FileInputStream(Path);
            byte[] c_s=new byte[1024];
           try{
            if(input.read(c_s)==-1)
           {
               System.out.println("文件读取完毕");
           }
               input.close();
           }
           catch (Exception e)
           {
               System.out.println(e.getMessage());
           }
            String res = new String(c_s, StandardCharsets.UTF_8);
            System.out.println(res.trim());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        //输入流
        FileOutputStream fos=null;
        try {
            //依然两种方法
            fos = new FileOutputStream(Path,true);
            String inputString="测试FileOutputStream";
            try {
                fos.write(inputString.getBytes());
                System.out.println("写入完成");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        finally {
            if (fos != null) {
                try {
                    fos.close();
                }
                catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }

字符流

说明

适用于文本文件的读写呀,速度也很快

FileReader         FileWriter

输出流                输入流(覆盖/追加)

import java.io.FileWriter;
import java.io.FileReader;
public static void FZ_FileReadWrite() {
        //以字符的方式写入
        FileWriter fw = null;
        String Path = "F://a.txt";
        try {

            //同上面的字节写入一样,加true为追加
            fw = new FileWriter(Path,true);
            String inputString = "写入要";
            fw.write(inputString);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }

        //文件读出
        FileReader fd=null;
        try {
            fd=new FileReader(Path);
            char[] reader=new char[1024];
            try {
                //返回值为非空格字符个数
                int length=fd.read(reader);
                System.out.println("实际字有:"+length);
                //新建拼接字符串
                StringBuilder stringBuilder=new StringBuilder();
                //将非空格字符拼接
                for (int i = 0; i < length;i++) {
                     stringBuilder.append(reader[i]);
                }
                System.out.println(stringBuilder.toString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

缓冲流

说明

这是最常用的,性能也不错的读写方式呀!

读取文件

    public static void Buffer_()
    {
        String path="F:\\JAVA EE Preject\\untitled2\\KotlinPratice\\src\\helloworld.kt";
//可以看出是越封装越深入        
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path)))){
            String printString;
            //每次读一行
            while ((printString=bufferedReader.readLine())!=null)
            {
                //每次输出一行
                System.out.println(printString);
            }
        }
        catch (Exception e) {
            System.out.println("搓搓");
        }
    }

复制文件(包含了写入文件) 

    public static void copyFile()
    {
        String path1="F:\\JAVA EE Preject\\untitled2\\KotlinPratice\\src\\helloworld.kt";
        String path="F:\\JAVA EE Preject\\untitled2\\KotlinPratice\\src\\helloworld.txt";
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path1)));
             BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path))))) {
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                bufferedWriter.write(line+"\r\n");
            }
        }
        catch (Exception e)
        {
            System.out.println("踩踩踩");
        }
    }

性能比较

文件大小读写方式耗时
30M普通文件流50-60 ms
缓存流32-35 ms
随机文件方式40-50 ms
内存映射文件50-60 ms
461M普通文件流1300-2300 ms
缓存流1700-2000 ms
随机文件方式1300-3000 ms
内存映射文件890-1000 ms
1.47G普通文件流11s
缓存流9s
随机文件方式10s
内存映射文件3s(首次较慢)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

桂亭亭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值