BluemSun 后端: IO简单预习

BluemSun 后端: IO简单预习

  • 在java程序中,对于数据的输入、输出操作以“流”(stream)方式进行;

分类

  • java.io包定义了多个流类型;
    1. 按数据流的方向不同分为输入流,输出流(在程序角度看);
    2. 按处理数据单位不同分为字节流,字符流;
    3. 按功能不同分为节点流,处理流;
      • 节点流:可以从一个特定的数据源(节点)读写数据;
      • 处理流:“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更强大的读写功能;
  • 在这里插入图片描述

字节流

1.InputStream基本方法(向程序读入)
  • int read() throws IOException

    读取一个子节并以整数形式返回,若返回-1为输入流末尾。

  • int read(byte[] buffer) throws IOException

    读取一系列字节并存储在数组buffer,返回实际读取子节数,若读取前已到输入流末尾返回-1。

  • int read(byte[] buffer, int offset,int length)throws IOException

    读取length个子节,并存储到字节数组buffer,从offset位置开始。返回读取的字节数,若读取前已到输入流末尾返回-1。

  • void close() throws IOException

    关闭流释放内存资源。

  • long skip(long n) throws IOException

    跳过n个字节不读,返回跳过的字节数。

2.OutputStream基本方法(程序向外输出)
  • void write(int b) throws IOException

    向输出流中写入一个字节数据,该字节数据为参数b的低8位。

  • void write(byte[] b) throws IOException

    将一个字节类型的数组中的数据写入输出流。

  • void write(byte[] b, int off,int len)throws IOException

    将一个字节类型的数组中的从指定位置(off)开始的len个字节写入到输出流。

  • void close() throws IOException

    关闭流释放内存资源。

  • void flush(long n) throws IOException

    将输出流中缓冲的数据全部写到目的地。

字符流

1.Reader基本方法(程序读入)
  • 数据的处理单位为字符(16bit);

  • int read() throws IOException

    读取一个子符并以整数形式返回,若返回-1为输入流末尾。

  • int read(byte[] buffer) throws IOException

    读取一系列字符并存储在数组buffer,返回实际读取子节数,若读取前已到输入流末尾返回-1。

  • int read(char[] buffer, int offset,int length)throws IOException

    读取length个子符,并存储到字节数组buffer,从offset位置开始。返回读取的字节数,若读取前已到输入流末尾返回-1。

  • void close() throws IOException

    关闭流释放内存资源。

  • long skip(long n) throws IOException

    跳过n个字符不读,返回跳过的字节数。

2.Writer基本方法(程序输出)
  • 继承自Writer的流用于程序输出数据,数据单位为字符。

  • void write(int c) throws IOException

    向输出流中写入一个字符数据,该字节数据为参数c的低8位。

  • void write(char[] b) throws IOException

    将一个字符类型的数组中的数据写入输出流。

  • void write(char[] b, int off,int len)throws IOException

    将一个字符类型的数组中的从指定位置(off)开始的len个字符写入到输出流。

  • void write(String string) throws IOException

    将一个字符串中的字符写入到输出流。

  • void write(String string, int off,int len)throws IOException

    将一个字符串从指定位置(off)开始的len个字符写入到输出流。

  • void close() throws IOException

    关闭流释放内存资源。

  • void flush(long n) throws IOException

    将输出流中缓冲的数据全部写到目的地。

节点流

code
  • FileInputStream(从文件接收):

      package com.nenu;
      import java.io.*;
      public class io {
          public static void main(String[] args) {
              int b=0;//接收程序从文件读的值
              FileInputStream in=null;//声明流
              
              try{
                  in=new FileInputStream("路径");//新建并连接
              }catch (FileNotFoundException e) {
                  System.out.println("找不到指定文件");
                  System.exit(-1);
              }
              
              try {
                  long num=0;
                  while ((b=in.read())!=-1) {//从in所连接的文件读入的值不为-1时执行
                      System.out.println((char)b);//输出b所对相应的char类型
                      num++;//计数
                  }
                  in.close();
                  System.out.println("共读取了"+num+"个字节");
              } catch (IOException e1) {
                  System.out.println("文件读取错误");
                  System.exit(-1);
              }
          }
      }
    
  • FileOutputStream(向文件读入):

    package com.nenu;
    import java.io.*;
    public class io {
        public static void main(String[] args) {
            int b=0;//接收程序从文件读的值
            FileInputStream in=null;//向程序输入的流
            FileOutputStream out=null;//程序向外输出的流
            try{
                in=new FileInputStream("路径");
                out=new FileOutputStream("路径");
                while ((b=in.read())!=-1) {
                    out.write(b);
                }
                in.close();
                out.close();
            }catch (FileNotFoundException e) {
                System.out.println("找不到指定文件");
                System.exit(-1);
            } catch (IOException e1) {
                System.out.println("文件复制错误");
                System.exit(-1);
            }
            System.out.println("文件已复制");
        }
    }
    
  • FileReader(读文件)

    ackage com.nenu;
    import java.io.*;
    public class io {
        public static void main(String[] args) {
            FileReader fr=null;
            int c=0;
            try {
                fr=new FileReader("T.java");
                int in=0;
                while((c= fr.read())!=-1) {
                    System.out.println((char)c);
                }
                fr.close();
            } catch (FileNotFoundException e) {
                System.out.println("找不到指定文件");
            } catch (IOException E) {
                System.out.println("文件读取错误");
            }
        }
    }
    
    
  • FileWriter(写文件)

    package com.nenu;
    import java.io.*;
    public class io {
        public static void main(String[] args) {
            FileWriter fw=null;
            try {
                fw=new FileWriter("T.java");
                for (int c=0;c<=5000;c++) {
                    fw.write(c);
                }
                fw.close();
            } catch (IOException E) {
                E.printStackTrace();
                System.out.println("文件写入错误");
                System.exit(-1);
            }
        }
    }
    
    

处理流

缓冲流
  • 缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了新的方法。

  • BufferedReader

  • 在这里插入图片描述

    程序读入文件数据

    package com.nenu;
    import java.io.*;
    public class io {
        public static void main(String[] args) {
            try {
                FileInputStream fis=new FileInputStream("t.java");
                BufferedInputStream bis=new BufferedInputStream(fis);
                int c=0;
                System.out.println(bis.read());
                System.out.println(bis.read());
                bis.mark(100);
                //从第100个开始读
                for(int i=0;i<=10&&(c=bis.read())!=-1;i++) {
                    System.out.println(c);
                }
                System.out.println();
                bis.reset();
                //回到标记点
                for(int i=0;i<=10&&(c=bis.read())!=-1;i++) {
                    System.out.println(c);
                }
                bis.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  • BufferedWriter

  • 在这里插入图片描述

    程序向文件写数据

    package com.nenu;
    import java.io.*;
    public class io {
        public static void main(String[] args) {
            try {
                BufferedWriter bw =new BufferedWriter(new FileWriter("t.java"));
                BufferedReader br=new BufferedReader(new FileReader("t2.txt"));
                String s=null;
                for(int i=1;i<=100;i++) {
                    s=String.valueOf(Math.random());
                    bw.write(s);
                    bw.newLine();
                }
                bw.flush();
                while ((s=br.readLine())!=null) {
                    System.out.println(s);
                }
                bw.close();
                br.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
转换流
  • InputStreamReader和OutputStreamWriter用于字节数据到字符数据之间的转换。(字节流转换成字符流)

  • InputStreamReader和Inputstream“套接”。

  • OutputStreamWriter和OutputStream“套接”。

    package com.nenu;
    import java.io.*;
    public class io {
        public static void main(String[] args) {
            try {
                OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("t.txt"));
                osw.write("ssssmmsmsmmsmm");
                System.out.println(osw.getEncoding());
                osw.close();
                osw=new OutputStreamWriter(new FileOutputStream("t1.txt",true),"ISO8859_1");
                //不写true会覆盖掉原来的内容,后为字符编码
                osw.write("kdkkdkdkdkdkkdkkd");
                System.out.println(osw.getEncoding());
                osw.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
  • System.in

    package com.nenu;
    import java.io.*;
    import java.util.Locale;
    
    public class io {
        public static void main(String[] args) {
            InputStreamReader isr=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(isr);
            String s=null;
            try {
                s=br.readLine();
                while(s!=null) {
                    if(s.equalsIgnoreCase("exit"))break;
                    System.out.println(s.toUpperCase());
                    s=br.readLine();
                }
                br.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
数据流
  • DateInputStream和DateOutputStream分别继承InputStream和OutputStream,属于处理流,需套接在InputStream和OutputStream类型的节点流上。

  • 它提供了可以存取与机器无关的java原始类型数据(int,double等)的方法。

  • 构造方法

    • DateInputStream(InputStream in)
    • DateOutputStream(OutputStream in)
  • package com.nenu;
    import java.io.*;
    import java.util.Locale;
    
    public class io {
        public static void main(String[] args) {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            DataOutputStream dos=new DataOutputStream(baos);
            try {
                dos.writeDouble(Math.random());
                dos.writeBoolean(true);
                ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
                System.out.println(bais.available());
                DataInputStream dis=new DataInputStream(bais);
                System.out.println(dis.readDouble());
                System.out.println(dis.readBoolean());
                dis.close();
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
Print 流
  • PrintWriter和PrintStream属于输出流,分别针对字符和字节。

  • PrintWriter和PrintStream提供了重载的print。

  • PrintWriter和PrintStream的输出操作不会抛异常,通过检测错误状态获取错误信息。

  • 有自动flush功能。

    • 打印字符

      package com.nenu;
      import java.io.*;
      import java.util.Locale;
      
      public class io {
          public static void main(String[] args) {
              PrintStream ps=null;
              try {
                  FileOutputStream fos=new FileOutputStream("t.txt");
                  ps=new PrintStream(fos);
              } catch (IOException e) {
                  e.printStackTrace();
              }
              if(ps!=null) {
                  System.setOut(ps);
              }
              int in=0;
              for(char c=0;c<=6000;c++) {
                  System.out.print(c+" ");
                  if(in++>=100) {
                      System.out.println();
                      in=0;
                  }
              }
          }
      }
      
      
    • 日志

      package com.nenu;
      import java.io.*;
      import java.util.Date;
      import java.util.Locale;
      
      public class io {
          public static void main(String[] args) {
             String s=null;
             BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
             try {
                 FileWriter fw=new FileWriter("t.txt");
                 PrintWriter log=new PrintWriter(fw);
                 while((s=br.readLine())!=null) {
                     if(s.equalsIgnoreCase("exit"))break;
                     System.out.println(s.toUpperCase());
                     log.println("----");
                     log.println(s.toUpperCase());
                     log.flush();
                 }
                 log.println("==="+new Date()+"===");
                 log.flush();
                 log.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
              
          }
      }
      
      
Object流
  • 将Object写入或读出

    package com.nenu;
    import java.io.*;
    import java.util.Date;
    import java.util.Locale;
    
    public class io {
        public static void main(String[] args) {
            try {
                T t=new T();
                t.k=8;
                FileOutputStream fos=new FileOutputStream("t.txt");
                ObjectOutput oos=new ObjectOutputStream(fos) {
                };
                oos.writeObject(t);
                oos.flush();
                oos.close();
                
                FileInputStream fis=new FileInputStream("t.txt");
                ObjectInputStream ois=new ObjectInputStream(fis);
                T tReaded=(T)ois.readObject();
                System.out.println(tReaded.i+" "+tReaded.j);
            } catch (Exception e) {
                e.printStackTrace();
            } 
           
        }
    }
    class T implements Serializable {
        int i=10;
        int j=9;
        double d=2.3;
        transient int k=15;//transient序列化时透明,不读入。
    }
    //Serializable序列化接口标记类序列化
    
  • externalizable接口

    • 继承了Serializable

    • 两个方法

      • void readExternal(ObjectInput in)

        读ObjectInput in

      • void writeExternal(ObjectInput in)

        写入ObjectInput in

文章参考于 尚学堂-马士兵-java

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值