java基础-IO框架

的概念

内存与存储设备之间传输数据的通道。

流的分类

按方向

输入流:将《存储设备》中的内容读入到<内存>中。

输出流:将<内存>中的内容写入到<存储设备>中

按单位

字节流:以字节为单位,可以读写所有数据

字符流:以字符为单位,只能读写文本数据

字符流也可以用字节流的方式来处理0

按功能:

节点流:具有实际传输数据的读写功能

过滤流:在节点流的基础之上增强功能

File类

代表物理盘符中的一个文件或者文件夹

常用方法

createNewFile()//创建一个新文件夹

mkdir() //创建一个新目录

delete()//删除文件或空目录

exists()//判断File对象所代表的对象是否存在

getAbsolutePath()//获取文件的绝对路径

getName()//取得名字

getParent()//获取文件/目录所在的目录

isDirectory()//是否是目录

isFile()//是否是文件

length()//获得文件的长度

listFiles()//返回一个抽象路径名数组,列出目录中的所有内容

renameTo()//修改文件名为

createTempFile(String prefix,String suffix)//在默认临时文件目录中创建一个空文件,使用给定的前缀和后缀生成其名称

getPath()//将此抽象路径名转换为路径名字符串

hashcode()//计算此抽象路径名的哈希码

isDirectory()测试此抽象路径名表示的文件是否为目录

isHidden()测试此抽象路径名命名的文件是否为隐藏文件

list()//返回一个字符串数组,命名由此抽象路径名表示的目录中的文件和目录

listRoots()//列出可用的文件系统根

renameTo(File dest)重命名由此抽象路径名表示的文件

File类方法的使用

package com.james;
​
import java.io.File;
import java.io.IOException;
import java.util.Date;
​
public class TestFile01 {
​
    public static void main(String[] args) {
//      创建一个abc.txt的抽象文件
        File f = new File("abc.txt");
//      打印创建的文件的名称
        System.out.println(f);
//      将抽象路径转换为字符串
        System.out.println(f.getPath());
//      打印绝对路径(全路径)
        System.out.println(f.getAbsolutePath());
        
        try {
//          测试此文件是否存在
            if(f.exists()) {
                System.out.println(true);
//              返回此抽象路径名的父路径名字符串,如果此路径名未命名为父目录,则返回null。 
                System.out.println(f.getParent());
                
                //  lastModified()获取文件最后的修改时间(long类型)
                System.out.println(new Date(f.lastModified()));
                
                //  判断一个文件是否可读、可写、可执行、是否是隐藏文件
                System.out.println(f.canRead());
                System.out.println(f.canWrite());
                System.out.println(f.canExecute());
                System.out.println(f.isHidden());
                
                //
                System.out.println(f.isFile());
            }else {
                //  使用createNewFile()方法创建一个物理文件
                f.createNewFile();
                
                
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
​
}
package com.james;
​
import java.io.File;
​
public class TestFile03 {
​
    public static void main(String[] args) {
        File f = new File("xyz");
        
        try {
            if(!f.exists()) {
                // 创建由此抽象路径名命名的目录
                System.out.println(f.mkdir());;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(f.mkdir());;
    }
​
}
package com.james;
​
import java.io.File;
​
public class TestFile04 {
​
    public static void main(String[] args) {
        File f = new File("111\\222\\333");
        
        try {
            if(!f.exists()) {
                
                
                //  mkdirs()可以创建多级目录
                System.out.println(f.mkdirs());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
​
}
package com.james;
​
import java.io.File;
import java.util.UUID;
​
public class TestFile05 {
​
    public static void main(String[] args) {
        //UUID.randomUUID()可以用来生成16个长度并含有四个中划线的随机字符串
        //  几乎可以做到不重复
        String path = UUID.randomUUID().toString();
        
        path = path.replace("-", "");
        
        File f = new File(path);
        
        if(!f.exists()) {
//          生成16个长度随机字符串的文件夹
            f.mkdir();
        }
        System.out.println(f);
    }
}
package com.james;
​
import java.io.File;
import java.util.UUID;
​
public class TestFile06 {
​
    public static void main(String[] args) {
        //构建一个空白的16位随机字符串
        StringBuilder path = new StringBuilder("");
        
        for(int i = 0;  i < 100; i++) {
            path.append(UUID.randomUUID().toString().replace("-", "") + "\\");
        }
        //构建100层名称为16位随机字符串的文件夹
        File f = new File(path.toString());
        
        if(!f.exists()) {
            f.mkdirs();
        }
        System.out.println(f);
    }
}
​
package com.james;
​
import java.io.File;
​
public class TestFile10 {
​
    public static void main(String[] args) {
        printFile("C:\\java2103\\code\\Days22Thread", "java");
    }
    
    /**
     * 在指定的path路径下查找指定后缀suffix的文件
     * @param path 路径
     * @param suffix 后缀
     */
    public static void printFile(String path, String suffix) {
        File f = new File(path);
        
        //  如果f对象是一个文件
        if(f.isFile()) {
            if(path.endsWith(suffix)) { //  文件以suffix结尾
                System.out.println(path);
            }
            return;
        }
        
        //  得到该文件夹下的所有子文件以及子文件夹,并以数组的形式存在
        String[] list = f.list();   
        
        //  遍历该文件夹下的所有子文件以及子文件夹
        for (String s : list) {
            
            //  以父目录和子文件/子文件夹字符串创建一个新的File对象
            File ff = new File(path, s);
            
            if(ff.isFile()) {   //  该File对象是一个文件
                if(s.endsWith(suffix)) {
                    System.out.println(ff.getAbsolutePath());
                }
            }else {
                
                //  File.separator多层目录分隔符   
                printFile(path + File.separator + s, suffix);
            }
        }
    }
}

拓展:

package practice0422;
​
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class TestFile01 {
    static List<String> listFile = new ArrayList<>();
    public static void main(String[] args) {
        List<String> list = printFile("D:\\java\\class code\\Days24FileDemo","String ...", "java","class");
//      System.out.println(list);
        for (String st : list) {
            System.out.println(st);
        }
    }
    
    /**
     * 在指定的path路径下查找的文件(使用可变长参数)
     * @param path 路径
     * @param suffix 后缀
     * 返回值为list
     */
    public static List<String> printFile(String path, String ...suffixs) {
        
        File f = new File(path);
        
        //  如果f对象是一个文件
        if(f.isFile()) {
            for (String suffix : suffixs) {
                if(path.endsWith(suffix)) { //  文件以suffix结尾
                    System.out.println(path);
                }
            }
            return listFile;
        }
        //f不是文件,是文件夹
        //  得到该文件夹下的所有子文件以及子文件夹,并以数组的形式存在
        String[] list = f.list();   
        
        //  遍历该文件夹下的所有子文件以及子文件夹
        for (String s : list) {
            
            //  以父目录和子文件/子文件夹字符串创建一个新的File对象
            File ff = new File(path, s);
            
            if(ff.isFile()) {   //  该File对象是一个文件
                for (String suffix : suffixs) {
                    if(s.endsWith(suffix)) {
//                      System.out.println(ff.getAbsolutePath());
                        listFile.add(ff.getAbsolutePath());
                    }
                }
            }else {
                
                //  该File对象是一个文件夹   
                printFile(path + File.separator + s, suffixs);
            }
        }
        return listFile;
    }   
}

字节流

字节流的父类(抽象类):

​ 字节输入流InputStream:

​ public int read(){}

​ public int read(byte[] b){}

​ public int read(byte[] b,int off,int len){}

​ 字节输出流OutputStream:

​ public void write(){}

​ public void write(byte[] b){}

​ public void write(byte[] b,int off,int len){}

字节节点流

FileOutputStream:

​ public void write(byte[] b) //一次写多个字节,将b数组中所有字节,写入输出流

FileInputStream:

​ public int read(byte[] b) //从流中读取多个字节,将读到内容存入B数组,返回实际读到的字节数,如果达到文件的尾部,则返回-1

字节过滤流

缓冲流

BufferedOutputSream/BufferedInputStream

​ 提高IO效率,减少访问磁盘的次数;

​ 数据存储在缓冲区中,flush是将缓存区的内容写入文件中,也可以直接close

对象流

ObjectOutputStream/ObjectInputStream

​ 增强了缓冲区功能

​ 增强了读写8种基本数据类型和字符串功能

​ 增强了读写对象的功能

​ readObject() 从流中读取一个对象

​ writeObject(Object obj) 从流中写入一个对象

对象的读取与写入

对象的写入

package com.james;
​
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
​
public class TestObjectStream01 {
​
    public static void main(String[] args) {
        Student s = new Student(9527, "huanan", 100);
        
        System.out.println(s);
        
        File f = new File("stu.txt");
//      声明一个对象流写入器来接收对象 
        ObjectOutputStream oos = null;
//      声明一个字节流写入器,接收对象中的内容     
        FileOutputStream fos = null;
        
        try {
//          使用文件对象创建字节写入器对象
            fos = new FileOutputStream(f);
//          使用文件对象创建对象写入器对象         
            oos = new ObjectOutputStream(fos);
            
            oos.writeObject(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
//              后开的先关,先开的后关
                if(oos != null) {
                    oos.close();
                    oos = null;
                }
                if(fos != null) {
                    fos.close();
                    fos = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("write done.");
    }
}

student类

package com.james;
​
import java.io.Serializable;
​
public class Student implements Serializable {
​
    int sid;
    String name;
    double score;
    
    public Student() {
    }
    
    public Student(int sid, String name, double score) {
        super();
        this.sid = sid;
        this.name = name;
        this.score = score;
    }
​
    @Override
    public String toString() {
        return "Student [sid=" + sid + ", name=" + name + ", score=" + score + "]";
    }
}

对象的读取

package com.james;
​
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
​
public class TestObjectStream02 {
​
    public static void main(String[] args) {
//      声明一个对象流读取器
        ObjectInputStream oos = null;
//      声明一个字节流读取器  
        FileInputStream fos = null;
        
        try {
            fos = new FileInputStream("stu.txt");
            oos = new ObjectInputStream(fos);
//          将Object对象强转回student对象
            Student s = (Student)oos.readObject();
            
            System.out.println(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                if(oos != null) {
                    oos.close();
                    oos = null;
                }
                if(fos != null) {
                    fos.close();
                    fos = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("read done.");
    }
}

获取文件指针的索引

package com.james;
​
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
​
public class TestRandomAccessFile01 {
    
    private static RandomAccessFile raf = null;
​
    public static void main(String[] args) {
        try {
            //  创建RandomAccessFile对象,文件名以及文件的访问方式rw代表可读可写
            raf = new RandomAccessFile("raf.txt", "rw");
            
            //  RandomAccessFile对象的getFilePointer()可以获取文件指针的索引
            System.out.println(raf.getFilePointer());
            
            raf.write("helloworld".getBytes());
            
            System.out.println(raf.getFilePointer());
            
            raf.writeInt(1000);
            
            System.out.println(raf.getFilePointer());
            
            raf.write(100);
​
            System.out.println(raf.getFilePointer());
            
            raf.writeBoolean(true);
​
            System.out.println(raf.getFilePointer());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(raf != null) {
                    raf.close();
                    raf = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
​
}
package com.james;
​
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
​
public class TestRandomAccessFile02 {
    
    private static RandomAccessFile raf = null;
​
    public static void main(String[] args) {
        try {
            //  创建RandomAccessFile对象,文件名以及文件的访问方式rw代表可读可写
            raf = new RandomAccessFile("raf.txt", "r");
            
//          byte[] b = new byte[10];
//          
//          raf.read(b);
            
//          System.out.println(new String(b));
            
            //  可以使用RandomAccessFile对象的skipBytes()来跳过指定字节,
            //      相当于直接可以通过程序来控制文件指针对象
            raf.skipBytes(10);
            
            int readInt = raf.readInt();
            
            System.out.println(readInt);
            
            int read = raf.read();
            
            System.out.println(read);
            
            boolean readBoolean = raf.readBoolean();
            
            System.out.println(readBoolean);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(raf != null) {
                    raf.close();
                    raf = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
​
}

字符流

字符流的父类(抽象类)

​ 字符输入流Reader:

​ public int read(){}

​ public int read(char[] c){}

​ public int read(char[] b, int off, int len){}

字符节点流

FileWriter:

​ public void write(String str) //一次写多个字符,将b数组中所有字符,写入输出流。

FileReader:

​ public int read(char[] c) //从流中读取多个字符,将读到内容存入C数组,返回实际读到的字符数;如果达到文件的尾部,则返回-1;

桥转换流;InputStreamReader/OutputStreamWriter

​ 可将字节流转换为字符流。

​ 可设置字符的编码方式。

字符过滤流

缓冲流:BufferedWriter/BufferedReader

​ 支持输入换行符

​ 可一次写一行、读一行

PrintWriter:

​ 封装了print()/println()方法,支持写入后换行。

​ 支持数据原样打印

对象序列化

所有的空接口的对象可序列化

作业:找出java中的4个空接口

1、java.rmi.Remote

2、java.lang.Cloneable

3、java.util.RandomAccess

4、java.io.Serializable

文件的写入与读取

文件内容的读取

ppackage com.james;
​
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
​
public class TestFileReader {
​
    public static void main(String[] args) {
        String str = "hello.txt";
​
        FileReader fr = null;
​
        try {
            //  使用一个表示文件的字符串创建一个FileReader文件写入器对象
            fr = new FileReader(str);
​
            int len;
            //  循环读取流中的所有数据,直到文件末尾
            //      注意,read()方法有一个“文件指针”概念,每read()一次,文件指针会后移一位
            //      所以不能频繁调用,借助len变量来做处理
            while ((len = fr.read()) != -1)
                System.out.print((char) len);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

​ 字符输出流Writer:

​ public void write(int n){}

​ public void write(String str){}

​ public void write(char[] c){}

文件内容的写入

package com.james;
​
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
​
public class TestFileWriter {
​
    public static void main(String[] args) {
        File f = new File("hello.txt");
        
        try {
            if(!f.exists()) {
                f.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        String str = "dajiaxinkule";
        
        //  声明一个FileWriter对象,文件写入器
        FileWriter fw = null;
        try {
            //  使用文件对象创建文件写入器对象
            fw = new FileWriter(f);
            
            //  调用文件写入器的write()方法完成字符串内容给f对象的写入
            fw.write(str);
            
            
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //  关闭流对象
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("write done.");
    }
​
}
​

copy一个文件的内容

package com.james;
​
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
​
public class TestFileCopy {
​
    public static void main(String[] args) throws IOException {
//      创建一个文件读取器
        FileReader fr = null;
//      创建一个文件写入器
        FileWriter fw = null;
        
        fr = new FileReader("hello.txt");
//      创建一个新文件
        File f = new File("world.txt");
        
        //  即使文件不存在,FileWrite也会自动创建该文件并进行内容地写入
//      if(!f.exists()) {
//          f.createNewFile();
//      }
//      创建一个缓存流对象
        StringBuilder sb = new StringBuilder();
//      读取原文件
        int len;
        while((len = fr.read()) != -1) {
            sb.append((char)len);
        }
        
        System.out.println("read done!");
        fw = new FileWriter(f);
//      将原文件读取到的字符串写入到新文件
        fw.write(sb.toString());
        
        System.out.println("write done!");
        
        fr.close();
        fw.close();
    }
}

IO框架的作用

对文件或者文件夹进行操作,也可以对文件里的内容进行操作。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值