java-常用的IO流

流的分类

  1. 操作数据单位:字节流、字符流
  2. 数据的流向:输入流、输出流
  3. 流的角色:节点流、处理流

流的体系结构

抽象基类节点流(或文件流)缓冲流转换流对象流
InputStreamFileInputStreamBufferedInputStreamObjectInputStream
OutputStreamFileOutputStreamBufferedOutputStreamObjectOutputStream
ReaderFileReaderBufferedReaderInputStreamReader
WriterFileWriterBufferedWriterOutputStreamWriter

节点流(文件流)

  • 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
  • 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理

FileReader && FileWriter

  1. read():返回读入的一个字符。如果达到文件末尾,返回-1
  2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
  3. 读入的文件一定要存在,否则就会报FileNotFoundException。
使用字符流写入文件
   //向文件写入
    @Test
    public void fileWriterTest(){
        File file = new File("test.txt");
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            fileWriter.write("MY NAME IS REFINE\n");
            fileWriter.write("what is your name?\n");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
使用字符流读取文件
//  读取文件
    @Test
    public void FileReaderTest(){
        File file = new File("test.txt");
        FileReader fileReader=null;
        try {
           fileReader = new FileReader(file);
           //读取一个字符, 如果达到文件末尾,返回-1
//            int data = fileReader.read();
//            while (data != -1){
//                System.out.print((char)data);
//                 data = fileReader.read();
//            }
            int data;
            while((data = fileReader.read()) != -1){
                System.out.print((char) data);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
使用字符流复制文件内容到另一个文件
    @Test
    public void fileReaderFileWriterTest(){
        File file = new File("test.txt");
        File file1 = new File("refine.txt");
        FileReader fr=null;
        FileWriter fw=null;
        try {
            fr = new FileReader(file);
            fw = new FileWriter(file1);
            int len;
            char[] cbuf=new char[128];
            while ((len = fr.read(cbuf)) != -1){
                for (int i=0;i<len;i++){
                    System.out.print(cbuf[i]);
                }
                fw.write(cbuf,0,len);
//                String str=new String(cbuf,0,len);
//                fw.write(str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

FileInputStream && FileOutputStream

  • read():返回读入的一个字节。如果达到文件末尾,返回-1
使用字节流复制文件内容到另一个文件
@Test
    public void fileInputOutputStreamTest(){
        FileInputStream fis=null;
        FileOutputStream fos=null;
        try {
            File srcFile = new File("kuangbiao.mp4");
            File destFile = new File("789.mp4");
            if (!destFile.exists()){
                destFile.createNewFile();
            }
             fis = new FileInputStream(srcFile);
             fos = new FileOutputStream(destFile);

             int len;
             byte[] bytes=new byte[128];
             while ((len = fis.read(bytes)) != -1){
                 fos.write(bytes,0,len);
             }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

处理流

缓冲流

字节缓冲流:BufferedInputStream && BufferedInputStream
复制文件内容到另一个文件
    @Test
    public void bufferedInputOutputStreamTest(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        FileInputStream fis = null;
        FileOutputStream fos = null ;
        try {
            File srcFile = new File("kuangbiao.mp4");
            File destFile = new File("789.mp4");
            if (!destFile.exists()){
                destFile.createNewFile();
            }
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            bis=new BufferedInputStream(fis);
            bos=new BufferedOutputStream(fos);
            byte[] bytes=new byte[1024];
            int len;
            while (( len=bis.read())!=-1){
                bos.write(bytes,0,len);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
字符缓冲流:BufferedReader && BufferedWriter
  • readLine():逐行读取。达到文件末尾,返回NULL;
  • read():返回读入的一个字节。如果达到文件末尾,返回-1
复制文件内容到另一个文件
    @Test
    public void bufferedReaderWriterTest(){
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            File srcFile = new File("test.txt");
            File destFile = new File("lucy.txt");
            if (!destFile.exists()){
                destFile.createNewFile();
            }
            FileReader fr = new FileReader(srcFile);
            FileWriter fw = new FileWriter(destFile);
            
            br = new BufferedReader(fr);
            bw = new BufferedWriter(fw);

//            char[] cbuf=new char[1024];
//            int len;
//            while ((len = br.read(cbuf)) != -1){
                for(int i =0;i < len;i++){
                    System.out.println(cbuf[i]);
                }
//                bw.write(cbuf,0,len);
                bw.flush();
//            }

            String data;
            while((data = br.readLine())!= null){
//                bw.write(data + "\n");
                bw.write(data);
                bw.newLine();
            }

转换流:InputStreamReader && OutputStreamWriter

  • 属于字符流
  • InputStreamReader:将一个字节的输入流转换为字符的输入流
  • OutputStreamWriter:将一个字符的输出流转换为字节的输出流
复制文件内容到另一个文件
    @Test
    public void inputStreamReaderOutputStreamWriterTest(){
        InputStreamReader isr= null ;
        OutputStreamWriter osw =null;

        try {
            File file = new File("test.txt");
            File file1 = new File("test_gbk.txt");

            FileInputStream fis=new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(file1);

            isr=new InputStreamReader(fis,"UTF-8");
            osw=new OutputStreamWriter(fos,"ASCII");

            char[] cbuf=new char[1024];
            int len;
            while ((len = isr.read(cbuf))!=-1){
//                for (int i=0;i<len;i++){
//                    System.out.print(cbuf[i]);
//                }
                osw.write(cbuf,0,len);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(isr != null){
                try {
                    isr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(osw != null){
                try {
                    osw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

标准输入、输出流:System.in && System.out

  • System.in和System.out分别代表了系统标准的输入和输出设备
  • System.in的类型是InputStream
  • System.out的类型是PrintStream
  • 重定向:通过System类的setIn,setOut方法对默认设备进行改变。
        BufferedReader br=null;
        try {
            InputStreamReader isr=new InputStreamReader(System.in);

            br = new BufferedReader(isr);
            while (true){
                System.out.println("Please input string:\t");
                String data = br.readLine();
                if("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){
                    System.out.println("exit program...");
                    break;
                }
                String upperCase=data.toUpperCase();
                System.out.println(upperCase);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        Scanner scanner=new Scanner(System.in);
        while (true){
            System.out.println("Please input string:\t");
            String next = scanner.next();
            if("e".equalsIgnoreCase(next) || "exit".equalsIgnoreCase(next)){
                System.out.println("exit program...");
                break;
            }

            String upperCase = next.toUpperCase();
            System.out.println(upperCase);
        }

打印流:PrintStream && PrintWriter

 		PrintStream ps =null;
        try {
            FileOutputStream fos=new FileOutputStream("day02\\text8.txt");
            ps=new PrintStream(fos,true);
            if(ps != null){
                System.setOut(ps);
            }
            
            for (int i = 0; i <= 255; i++) { // 输出ASCII字符
                System.out.print((char) i);
                if (i % 50 == 0) { // 每50个数据一行
                    System.out.println(); // 换行
                }
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            if(ps != null){
                ps.close();
            }
        }
        

数据流:DataOutputStream && DataInputStream

        DataOutputStream dos= null;
        DataInputStream dis= null;
        try {
            dos = new DataOutputStream(new FileOutputStream("test10.bat"));
            dis = new DataInputStream(new FileInputStream("test10.bat"));
            dos.writeUTF("I am a teacher。");
            dos.flush();
            dos.writeDouble(23.5652);
            dos.flush();
            dos.writeUTF("refine");
            dos.flush();
            
            String utf = dis.readUTF();
            double aDouble = dis.readDouble();
            String urf1 = dis.readUTF();
            System.out.println(utf);
            System.out.println(aDouble);
            System.out.println(urf1);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(dos != null){
                try {
                    dos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(dis != null){
                try {
                    dis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

对象流:ObjectOutputStream && ObjectInputStream

  • 序列化:把内存中的Java对象转换成平台无关的二进制流,从而允许把这种
    二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点;
  • 反序列化:当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。
  • 要想一个java对象是可序列化的,需要满足相应的要求: public static final long serialVersionUID = 125478745867710L;
public class Animal implements Serializable{
    public static final long serialVersionUID = 125478745867710L;
    String name;
    int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
//      序列化:将内存中的java对象保存到磁盘中或通过网络传输出去C
    @Test
    public  void  objectOutputStreamTest(){
        ObjectOutputStream oop= null;
        try {
            oop = new ObjectOutputStream(new FileOutputStream("test9.txt"));
            oop.writeObject(new Animal("cat",3));
            oop.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(oop != null){
                try {
                    oop.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

//	 反序列化:将磁盘文件中的对象还原为内存中的一个java对象
	@Test
    public  void  objectInputStreamTest(){
        ObjectInputStream ois=null;

        try {
            ois=new ObjectInputStream(new FileInputStream("test9.txt"));
            Animal animal = (Animal) ois.readObject();
            System.out.println(animal);

        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

随机存取文件流:RandomAccessFile

  • 直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
  • RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
  • 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
    如果写出到的文件存在,则会对原有文件内容进行覆盖;
  • 可以实现RandomAccessFile“插入”数据;
@Test
    public void randomAccessFileTest1(){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile("test.txt", "rw");
            raf.seek(5);
            // 写入时覆盖原有数据
//            raf.write("refine".getBytes());

            StringBuilder stringBuilder=new StringBuilder((int) new File("test.txt").length());
            byte[] buffer=new byte[1024];
            int len;
            while ((len = raf.read(buffer)) != -1){
                stringBuilder.append(new String(buffer,0,len));
            }
            // 插入数据
            raf.seek(5);
            raf.write("refine".getBytes());
            raf.write(stringBuilder.toString().getBytes());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            if ( raf != null){
                try {
                    raf.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

使用RandomAccessFile复制文件内容到另一个文件

// 文件内容的复制
    @Test
    public void randomAccessFileTest2(){
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;

        try {
            raf1 = new RandomAccessFile("kuangbiao.mp4", "r");
            raf2 = new RandomAccessFile("refine.mp4", "rw");

            byte[] bytes=new byte[1024];
            int len;
            while ((len = raf1.read(bytes)) != -1){
                raf2.write(bytes,0,len);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if( raf1 != null){
                try {
                    raf1.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if( raf2 != null){
                try {
                    raf2.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

梅尝酥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值