Java--IO学习笔记

  1. 什么是IO?

    通过IO可以完成硬盘文件的读和写。

  2. java io流四大类:

    InputStream(字节输入流)				Reader(字符输入流)
    OutputStream(字节输出流)				Writer(字符输出流)
    所有的方法都实现了java.io.Closeable接口,都是可关闭的,都有close()方法
    
  3. InputStream读取数据:

    public static void main(String []args) throws IOException {
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream("temp.txt");
                byte[] arr = new byte[1024];
                int len = -1;
                while ((len = fileInputStream.read(arr)) != -1){
                    System.out.println(new String(arr,0,len));//转换成字符串,将返回来的ASCII解码
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(fileInputStream != null){
                    fileInputStream.close();
                }
            }
        }
    
  4. 文件的复制:

     FileOutputStream fileOutputStream = null;
            FileInputStream fileInputStream = null;
            try {
                fileOutputStream = new FileOutputStream("src/Day_02/temp.txt");
                byte[] arr = new byte[1024];
                int len = 0;
                fileInputStream = new FileInputStream("temp.txt");
                while ((len = fileInputStream.read(arr)) != -1){
                    fileOutputStream.write(arr,0,len);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(fileOutputStream != null){
                    fileOutputStream.close();
                }
                if(fileInputStream != null){
                    fileInputStream.close();
                }
            }
    
  5. 缓冲流输入:

    BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader("src\\Day_02\\Java_Io_001.java"));
                String line = "";
                while((line = reader.readLine()) != null){
                    System.out.println(line);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(reader != null){
                    reader.close();
                }
            }
    
  6. 缓冲流复制文件:

    BufferedReader reader = null;
            BufferedWriter writer = null;
            try {
                reader = new BufferedReader(new FileReader("src\\Day_02\\Java_Io_001.java"));
                writer = new BufferedWriter(new FileWriter("temp.java"));
                String line = null;
                while ((line = reader.readLine()) != null){
                    writer.write(line);
                    writer.write("\n");
                }
                writer.flush();//输出缓冲流必须用flush(),不然输出的文件没有数据
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(reader != null){
                    reader.close();
                }
                if(writer != null){
                    writer.close();
                }
            }
    
  7. 标准输出流:

     PrintStream printStream = new PrintStream("temp.txt");
            System.setOut(printStream);//设置输出的位置,不再输出到控制台上
            System.out.println("hello");
            System.out.println("Worl1d");
            System.out.println("!!!Pointer");
    
  8. 标准输出流的应用:

     PrintStream printStream = new PrintStream(new FileOutputStream("temp.txt",true));//true:是追加数据
            System.setOut(printStream);
    
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String s = dateFormat.format(date);
            System.out.println(s  + " : " + msg);
    
     Logger.log("System.out.println");
            Logger.log("True");
            Logger.log("right");
    
  9. File类不能完成文件的读和写,File对象代表文件和目录路径名的抽象表示形式。

  10. File常用方法的使用:

    1. exists、mkdir:

      if(!file.exists()){ //exists:判断文件或目录是否存在
                  file.mkdir(); //mkdir创建file对象所在的路径
      }
      
    2. mkdirs:

      File file = new File("D:\\a\\b\\c\\d");
              if(!file.exists()){
                 file.mkdirs();//多重目录创建,无论父目录是否有没有创建
              }
      
    3. getParent()、getAbsolutePath():

      File file = new File("D:\\eclipse-2020-03\\eclipse");
              String parent = file.getParent();//获取父目录的路径
              String absolutePath = file.getAbsolutePath();//获取file对象的绝对路径
              System.out.println(parent);
              System.out.println(absolutePath);
      
    4. getName()、isDirectory()、isFile():

      File f1 = new File("D:\\course\\open.txt");
      String name = f1.getName(); //获取file文件名
      
      System.out.println(f1.isDirectory());//判断是否为一个目录
      
      
      System.out.println(f1.isFile());//判断是否为一个文件
      
    5. listFiles():

      File f = new File("D:\\apache-tomcat-9.0.30\\backup");
      //File[] listFiles() 获取当前目录下所有的子文件
              File[] files = f.listFiles();
              for (File file:files){
                 System.out.println(file.getName());
      }
      
  11. 目录的复制:

     public static void main(String []args) throws IOException {
            File srcFile = new File("F:\\32林佳泽");
            File destFile = new File("G:\\");
    
            //调用方法拷贝
            copyDir(srcFile,destFile);
        }
    
        public static void copyDir(File srcFile,File destFile) throws IOException {
            if(srcFile.isFile()){
    
                FileInputStream fileInputStream =  null;
                FileOutputStream fileOutputStream = null;
                try {
                    fileInputStream = new FileInputStream(srcFile);
                    String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(3);
                    fileOutputStream = new FileOutputStream(path);
                    byte[] arr = new byte[1024 * 1024];//一次赋值1MB
                    int len = 0;
                    while ((len = fileInputStream.read(arr)) != -1){
                        fileOutputStream.write(arr,0,len);
                    }
    
                    fileOutputStream.flush();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(fileInputStream != null){
                        fileInputStream.close();
                    }
                    if(fileOutputStream != null){
                        fileOutputStream.close();
                    }
                }
                return;//如果srcFile是一个文件的话,递归结束
            }
    
            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);
                    File newDir = new File(destDir);
                    if(!newDir.exists()){
                        newDir.mkdirs();
                    }
                }
    
                //递归调用
                copyDir(file,destFile);
            }
        }
    
  12. 序列化与反序列化:

    序列化:java对象存储到文件中。将java对象的状态保存下来的过程

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

  13. 序列化:

     student student = new student(12,"zs");
    
    
            ObjectOutputStream objectOutputStream = null;
            try {
                objectOutputStream = new ObjectOutputStream(new FileOutputStream("student"));
                //参与序列化和反序列化必须实现Serializable接口
                //起到标识的作用,
                //序列化
                objectOutputStream.writeObject(student);
            }catch (Exception e){
                e.printStackTrace();
            }finally{
                if(objectOutputStream != null){
                    objectOutputStream.close();
                }
            }
    
    
    class student implements Serializable {
        private int no;
        private String name;
    
        @Override
        public String toString() {
            return "student{" +
                    "no=" + no +
                    ", name='" + name + '\'' +
                    '}';
        }
    
        public student() {
        }
    
        public student(int no, String name) {
            this.no = no;
            this.name = name;
        }
    
        public int getNo() {
            return no;
        }
    
        public void setNo(int no) {
            this.no = no;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
    
  14. 反序列化的实现:

    ObjectInputStream objectInputStream = null;
            try {
                objectInputStream = new ObjectInputStream(new FileInputStream("student"));
                Object o = objectInputStream.readObject();
                System.out.println(o);
            }catch (Exception e){
                e.printStackTrace();
            }finally{
                if(objectInputStream != null){
                    objectInputStream.close();
                }
            }
    
  15. IO + Properties联合使用

    IO流:文件的读和写。

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

    userinfo:
        username=admin
    	password=123
    
    //java规范中要求:属性配置文件建议以.properties结尾,
     //其中properties是专门存放文件属性配置文件内容的一个类
    
    FileReader reader = new FileReader("src\\Day_03\\userinfo");
    
    
            //新建一个Map集合
            Properties properties = new Properties();
    
            properties.load(reader);//文件中的数据顺着管道加载到Map集合中,其中等号=左边做key,有便做value
    
            //通过key来获取value
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");
            System.out.println(username);
            System.out.println(password);
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值