zoukankan      html  css  js  c++  java
  • IO

    流的分类

    • 输入流、输出流
    • 字节流、字符流

    IO流四大家族

    • java.io.InputStream 字节输入流
    • java.io.OutputStream 字节输出流
    • java.io.Reader 字符输入流
    • java.io.Writer 字符输出流

    所有的流都实现了:

    ​ java.io.Closeable接口,都是可关闭的,都有close()方法。

    ​ 流是内存和硬盘之间的通道,用完之后要关闭,不然会占用很多资源。

    所有的输出流都实现了:

    ​ java.io.Flushable接口,都是可刷新的,都有flush()方法。

    ​ 输出流在最终输出后一定要记得flush()

    ​ 刷新表示将管道当作剩余未输出的数据强行输出完(清空管道)

    ​ 注意:如果没有flush()可能会导致丢失数据

    注意:在java中只要类名以Stream结尾的都是字节流。以Reader/Writer结尾的都是字符流。

    word文件不是普通文本,字符流只读普通文件(txt,java等),无法操作word,图片,视频等

    能用记事本编辑的都是普通文本文件

    需要掌握的流

    文件专属 缓冲流专属
    java.io.FileInputStream java.io.BufferedInputStream
    java.io.FileOutputStream java.io.BufferedOutputStream
    java.io.FileReader java.io.BufferedReader
    java.io.FileWriter java.io.BufferedWriter
    转换流 (将字节流转换成字符流) 数据流专属
    java.io.InputStreamReader java.io.DataInputStream
    java.io.OutputStreamWriter java.io.DataOutputStream
    对象专属流 标准输出流
    java.io.ObjectInputStream java.io.PrintWriter
    java.io.ObjectOutputStream java.io.PrintStream

    文件流

    FileInputStream

    FileInputStream fis = null;
    try {
        fis = new FileInputStream("D:\xyz\temp");		
        byte[] bytes = new byte[4];
        int readCount = 0;
        while ((readCount = fis.read(bytes)) != -1) {
            System.out.print(new String(bytes, 0, readCount));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    FileInputStream

    • int available() 返回流当中剩余的没有读到的字节数量

    • long skip(long n) 跳过几个字节不读

    FileInputStream fis = null;
    try {
        fis = new FileInputStream("D:\xyz\temp");		//abcdef
        System.out.println("总字节数量:" + fis.available());	//6
        //读一个字节
        //int readByte = fis.read();
        //还剩下可以读的字节数量是:5
        //System.out.println("剩下没有读的字节数量:" + fis.available());
        //这个方法有什么用?
        byte[] bytes = new byte[fis.available()];	//这种方式不太适合太大的文件,因为byte[]数组不能太大。
        int readCount = fis.read(bytes);
        System.out.println(new String(bytes));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    fis.skip(3);	//跳过3个字节
    System.out.println(fis.read());	//100
    

    fis.read() 读一个字节

    fis.read(bytes) 读的是数组的长度

    FileOutputStream

    FileOutputStream fos = null;
    try {
        //fis = new FileOutputStream("tempfile");此方法会重写文件内容慎用
        //FileOutputStream(String name, boolean append)
        //ture表示文件后追加
        fos = new FileOutputStream("tempfile",true);
        byte[] bytes = {97,98,99,100};
    
        fos.write(bytes);	//abcd
        fos.write(bytes,0,2);	//ab
        
        String s = "这是输出文本";
        byte[] bs = s.getBytes();
        fos.write(bs);
        //写完之后一定要刷新
        fos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    文件复制

    FileInputStream fis = null;
    FileOutputStream fos = null;
    
    try {
        fis=new FileInputStream("tempfile.pdf");
        fos=new FileOutputStream("copyfile.pdf");
    
        byte[] bytes = new byte[1024 * 1024]; //1MB(一次最多拷贝1MB)
        int readCount = 0;
        while((readCount = fis.read(bytes)) != -1) {
            fos.write(bytes,0,readCount);
        }
        fos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //分开try,不要一起try
        //一起try的时候,其中一个出现异常,可能会影响到另一个流的关闭。
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    

    FileReader

    FileReader reader = null;
    try {
        reader = new FileReader("readfile");
        char[] chars = new char[4];
        int readCount = 0;
        while ((readCount = reader.read(chars)) != -1) {
            System.out.print(new String(chars, 0, readCount));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    FileWriter

    FileWriter out = null;
    try {
        out = new FileWriter("inputfile.txt");
        char[] chars = {'我','是','中','国','人'};
        out.write(chars);
        out.write(chars,2,3);
        out.write("
    ");
        out.write("直接输入字符串");
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    复制普通文本文件

    FileReader in = null;
    FileWriter out = null;
    try {
        in = new FileReader("inputfile.txt");
        out = new FileWriter("copyfile.txt");
    
        char[] chars = new char[1024 * 512];	//1MB 因为char为2字节
        int readCount = 0;
        while ((readCount = in.read(chars)) != -1) {
            out.write(chars,0,readCount);
        }
        out.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    带有缓冲区的字符流

    自带缓冲不需要指定 char[ ] 数组 或 byte[ ] 数组

    BufferedReader

    FileReader reader =null;
    BufferedReader br = null;
    try {
        reader = new FileReader("inputfile.txt");
        // 当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流。
        // 外部负责包装的这个流,叫做:包装流,还有一个名字叫做:处理流。
        // 像当前这个程序来说:FileReader就是一个节点流。BufferedReader就是包装流/处理流。
        br = new BufferedReader(reader);
    
        // 读一行
        String firstLine = br.readLine();
        System.out.println(firstLine); // 第一行
        String secondLine = br.readLine();
        System.out.println(secondLine); // 第二行
    
        String s = null;
        while ((s = br.readLine()) != null) {
            System.out.print(s);
        }
        
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                // 关闭流
                // 对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭。(可以看源代码)
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    节点流和包装流

    /*//字节流
    FileInputStream in = new FileInputStream("inputfile.txt");
    
    //通过转换流转换(InputStreamReader将字节流转换成字符流)
    //in是节点流。reader是包装流。
    InputStreamReader reader = new InputStreamReader(in);
    
    //这个构造方法只能传一个字符流。不能传字节流。
    //reader是节点流。br是包装流。
    BufferedReader br = new BufferedReader(reader);*/
    
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("inputfile.txt")));
    
    String line = null;
    while ((line = br.readLine()) != null) {
        System.out.print(line);
    }
    
    //关闭最外层
    br.close();
    

    BufferedWriter

    //BufferedWriter out = new BufferedWriter(new FileWriter("copy"));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("copy")));
    out.write("hello world!");
    out.write("
    ");
    out.write("hello morning!");
    out.flush();
    out.close();
    

    数据流

    DataOutputStream

    /*
    java.io.DataOutputStream:数据专属的流。
    这个流可以将数据连同数据的类型一并写入文件。
    注意:这个文件不是普通文本文档。(这个文件使用记事本打不开。)
    */
    //创建数据专属的字节输出流
    DataOutputStream dos = new DataOutputStream(new FileOutputStream("data"));
    //写数据
    byte b = 100;
    short s = 200;
    int i = 300;
    long l = 400L;
    float f = 3.0F;
    double d = 3.14;
    boolean sex = false;
    char c = 'a';
    //写
    dos.writeByte(b);	//把数据以及数据的类型一并写入到文件当中。
    dos.writeShort(s);
    dos.writeInt(i);
    dos.writeLong(l);
    dos.writeFloat(f);
    dos.writeDouble(d);
    dos.writeBoolean(sex);
    dos.writeChar(c);
    
    //刷新
    dos.flush();
    //关闭最外层
    dos.close();
    

    可以理解为是个加密的文件

    按照什么类型写进去的就要按照什么类型读出来

    DataInputStream

    /*
    DataInputStream:数据字节输入流。
    DataOutputStream写的文件,只能使用DataInputStream去读。并且读的时候你需要提前知道写入的顺序。
    读的顺序需要和写的顺序一致。才可以正常取出数据。
    */
    DataInputStream dis = new DataInputStream(new FileInputStream("data"));
    //开始读
    byte b = dis.readByte();
    short s = dis.readShort();
    int i = dis.readInt();
    long l = dis.readLong();
    float f = dis.readFloat();
    double d = dis.readDouble();
    boolean sex = dis.readBoolean();
    char c = dis.readChar();
    
    System.out.println(b);
    System.out.println(s);
    System.out.println(i);
    System.out.println(l);
    System.out.println(f);
    System.out.println(d);
    System.out.println(sex);
    System.out.println(c);
    
    dis.close();
    
    

    标准输出流

    java.io.PrintStream

    /*
      java.io.PrintStream: 标准的字节输出流。默认输出到控制台。
    */
    //联合起来写
    System.out.println("hello world!");
    
    //分开写
    PrintStream ps = System.out;
    ps.println("hello");
    
    //标准输出流不需要手动close()关闭。
    //可以改变标准输出流的输出方向吗?可以
    /*
    //这些是之前System类使用过的方法和属性
    System.gc();
    System.currentTimeMillis();
    PrintStream ps2 = System.out;
    System.exit(0);
    */
    
    //标准输出流不再指向控制台,指向“Log”文件。
    PrintStream printStream = new PrintStream(new FileOutputStream("log",true));
    //修改输出方向,将输出方向修改到“Log”文件。
    System.setOut(printStream);
    //再输出
    System.out.println("hello world!");
    
    

    日志框架

    /*
    日志工具
    */
    public class Logger {
        /*
        记录日志的方法。
        */
        public static void log(String msg) {
            try {
                PrintStream out = new PrintStream(new FileOutputStream("log.txt",true));
                System.setOut(out);
                Date nowTime = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
                String strTime = sdf.format(nowTime);
                System.out.println(strTime + ": " + msg); 
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    

    java.io.File类

    不属于流

    文件和目录路径名的抽象表示形式

    /*
    File
    	1、File类和四大家族没有关系,所以File类不能完成文件的读和写。
    	2、File对象代表什么?
    		文件和目录路径名的抽象表示形式。
    		一个File对象有可能对应的是目录,也可能是文件。
    		File只是一个路径名的抽象表示形式。
    	3、需要掌握File类中常用的方法
    */
    //创建一个File对象
    File f1 = new File("D:\file");
    
    //判断是否存在
    System.out.println(f1.exists());
    
    //如果D:file不存在,则以文件的形式创建出来
    if(!f1.exists()) {
    	f1.createNewFile();
    }
    
    //如果D:file不存在,则以目录的形式创建出来
    if(!f1.exists()) {
    	f1.mkdir();
    }
    
    //多重目录
    File f1 = new File("D:/a/b/c/d/e/f");
    if(!f1.exists()) {
    	f1.mkdirs();
    }
    
    //获取父路径
    File f1 = new File("D:/a/b/c/d/e/f");
    String parentPath = f1.getParent();
    System.out.println(parentPath);
    
    File parentFile = f1.getParentFile();	//效果一样,返回值不一样
    System.out.println("获取绝对路径:" + parentFile.getAbsolutePath());
    System.out.println(f1.getAbsolutePath());
    

    常用方法

    //获取文件名
    fi.getName();
    
    //判断是否是一个目录
    fi.isDirectory();
    
    //判断是否是一个文件
    fi.isFile();
    
    //获取文件最后一次修改时间
    long haoMiao = f1.lastModified();	//这个毫秒是从1970年到现在的总毫秒数。
    //将总毫秒数转换成日期
    Date time = new Date(haoMiao);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
    String strTime = sdf.format(time);
    System.out.println(strTime);
    
    //获取文件大小
    f1.length();	//多少字节
    
    //File[] listFiles()
    //获取当前目录下所有的子文件。
    File f = new File("D:\a\b");
    File[] files = f.listFiles();
    //foreach
    for(File file : files){
        System.out.println(file.getAbsolutePath());
    }
    

    目录拷贝

    public static void main(String[] args){
        //拷贝源
        File srcFile = new File("D:\xyz\document");
        //拷贝目标
        File destFile = new File("C:\a\b\c\d\");
        //调用方法拷贝
        copyDir(srcFile,destFile);
    }
    
    private static void copyDir(File srcFile, File destFile){
        if(srcFile.isFile()){
            //srcFile如果是一个文件的话,递归结束
            //是文件的时候需要拷贝
            //一边读一边写
            FileInputStream in = null;
            FileOutputStream out =null;
            try{
                in = new FileInputStream(srcFile);
                String path = (destFile.getAbsolutePath().endsWith("\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\") + srcFile.getAbsolutePath().substring(3);
                out = new FileOutputStream(path);
                byte[] bytes = new byte[1024 * 1024];	//一次复制1MB
                int readCount = 0;
                while((readCount = in.read[bytes]) != -1){
                    out.write(bytes, 0, readCount);
                }
                out.flush();
            }catch(FileNotFoundException e){
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(out != null){
                    try{
                        out.close();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
                if(in != null){
                    try{
                        in.close();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
        //获取源下面的子目录
        File[] files = srcFile.listFiles();
        for(File file : files){
            //获取所有文件的(包括目录和文件)绝对路径
            //System.out.println(file.getAbsolutePath());
            if(file.isDirectory()){
                //新建对应的目录
                String srcDir = file.getAbsolutePath();
                String destDir = (destFile.getAbsolutePath().endsWith("\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\") + srcDir.substring(3);
                //System.out.println(destDir);
                File newFile = new File(destDir);
                if(!newFile.exists()){
                    newFile.mkdirs();
                }
            }
            //递归调用
            copyDir(file,destFile);
        }
    }
    

    对象流

    对象的序列化和反序列化

    序列化(Serialize):把Java对象从内存放到硬盘文件中,将Java对象的状态保存下来的过程。分为多个数据包发送,按序按列。(拆分对象)

    反序列化(DeSerialize):将硬盘上的数据重新恢复到内存当中,恢复成java对象。(组装对象)

    ObjectOutputStream

    Student s= new Student(111,"zhangsan");
    
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students"));
    //序列化对象
    oos.writeObject(s);
    
    oos.flush();
    oos.close();
    
    public class Student implements Serializable{	//实现一个可序列化接口
        ...
    }
    

    Java中接口有两种,一种是普通接口,另一种是标志接口。

    Serializable是一个标志性接口,没有任何方法,java虚拟机看到这个类实现了这个接口,可能会对这个类进行特殊待遇。

    Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号。

    这里没有手动写出来,java虚拟机会默认提供这个序列化版本号。

    ObjectInputStream

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students"));
    //开始反序列化,读
    Object obj = ois.readObject();
    //反序列化回来是一个学生对象,所以会调用学生对象的toString方法。
    System.out.println(obj);
    oos.close();
    

    序列化多个对象

    //ObjectOutputStream
    /*
    一次序列化多个对象呢?
    	可以,可以将对象放到集合当中,序列化集合
    提示:
    	参与序列化的ArrayList集合以及集合中的元素User都需要实现java.io.Serializable接口。
    */
    List<User> userList = new ArrayList<>(); 
    userList.add(new User(1,"zhangsan"));
    userList.add(new User(2,"lisi"));
    userList.add(new User(3,"lisi222"));
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users"));
    
    //序列化一个集合,这个集合对象中放了很多其他对象。
    oos.writeObject(userList);
    
    oos.flush();
    oos.close();
    
    //ObjectInputStream
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users"));
    //Object obj = ois.readObject();
    //System.out.println(obj instanceof List);
    List<User> userList = (List<User>)ois.readObject();
    for(User user : userList){
        System.out.println(user);
    }
    ois.close();
    

    transient关键字

    public class User implements Serializable{	
        private int no;
        //transient关键字表示游离的,不参与序列化。
        private transient String name;	//name不参与序列化操作
    }
    

    关于序列化版本号

    Java语言中是采用什么机制来区分类的?

    • 第一:首先通过类名进行比对,如果类名不一样,肯定不是同一个类。
    • 第二:如果类名一样,再怎么进行类的区别?靠序列化版本号进行区分

    序列化版本号意义:可以用来区分类

    这种自动生成的序列化版本号缺点是:一旦代码确定之后,不能进行后续的修改,因为只要修改,必然会重新编译,此时会生成全新的序列化版本号,这个时候java虚拟机会认为这是一个全新的类。

    最终结论:

    • 凡是一个类实现了Serializable接口,建议给该类提供一个固定不变的序列化版本号。
    • 这样,以后这个类即使代码修改了,但是版本号不变,java虚拟机会认为是同一个类。
    public class Student implements Serializable{
        //Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号。
        //这里没有手动写出来,java虚拟机会默认提供这个序列化版本号。
        //建议将序列化版本号手动的写出来。不建议自动生成
        private static final long serialVersionUID = 1L;
    }
    

    IO + Properties联合使用

    IO流:文件的读和写

    Properties:是一个Map集合,key和value都是String类型。

    userinfo

    username=admin
    password=123
    

    //text文件

    //在属性配置文件中 # 是注释

    //等号两边最好不要有空格

    //IO + Properties联合应用
    /*
    	想将userin fo文件中的数据加载到Properties对象当中。
    */
    //新建一个输入流对象
    FileReader reader = new FileReader("D:/userinfo")
        
    //新建一个Map集合
    Properties pro = new Properties();
    
    //调用Properties对象的load方法将文件中的数据加载到Map集合中。
    pro.load(reader);//文件中的数据顺着管道加载到Map集合中,其中等号=左边做key,右边做value
    
    //通过key来获取value
    String username = pro.getProperty("username");//建议key粘贴过来,直接写容易出错
    System.out.println(username);
    

    value可以直接修改

    经常变换的信息可以写到类似这样的文件当中

    IO + Properties的联合应用

    非常好的一个设计理念:

    ​ 以后经常改变的数据,可以单独写到一个文件中,使用程序动态读取。将来只需要修改这个文件的内容,java代码不需要改动,不需要重新编译,服务器也不需要重启。就可以拿到动态的信息。

    ​ 类似于以上机制的这种文件被称为配置文件。

    ​ 并且当配置文件中的内容格式是:

    ​ key1=value

    ​ key2=value

    ​ 的时候,我们把这种配置文件叫做属性配置文件

    ​ java规范中有要求:属性配置文件建议以.properties结尾,但这不是必须的。

    ​ 这种以.properties结尾的文件在java中被称为:属性配置文件。

    ​ 其中Properties是专门存放属性配置文件内容的一个类。

  • 相关阅读:
    Java学习--泛型
    java学习--自定义类的实例的大小比较和排序
    Java学习--枚举
    java学习--修饰符
    Java学习--变量
    POI--各种样式的XSSFCellStyle的生成
    POI 使用颜色字符串生成XSSFColor对象
    Others # 看到的一些創意 / 知乎不錯的提問/ Android安全
    RO # 不错站点
    Linux # Virtual Box VBoxGuestAdditions.iso
  • 原文地址:https://www.cnblogs.com/cnyl/p/14195111.html
Copyright © 2011-2022 走看看