javaSE基础-IO流

IO流

File类

基本概念

File类的一个对象,代表一个文件或一个文件目录(俗称文件夹)
File类声明在java.io包下
File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成
File类的对象常会作为参数传递到流的构造器中,指明读入或写出的"终点"

构造器使用

File(String pathname):指定路径名的字符串转换成一个抽象路径名

File(String parent, String child):指定父路径的字符串和子路径的字符串

File(File parent, String child):指定父路径的抽象路径名和子路径的字符串

示例:

@Test
public void test1(){
    //构造器1:
    File file1 = new File("hello.txt");
    File file2 = new File("/Users/jbb/java_project/pro01/hah.txt");
    //构造器2:
    File file3 = new File("/Users/jbb/java_project", "pro01");
    File file4 = new File("/User" + File.separator + "jbb");

    //构造器3:
    File file5 = new File(file3, "name.txt");

    System.out.println(file1);// hello.txt
    System.out.println(file2);// /Users/jbb/java_project/pro01/hah.txt
    System.out.println(file3);// /Users/jbb/java_project/pro01
    System.out.println(file4);// /User/jbb
    System.out.println(file5);// /Users/jbb/java_project/pro01/name.txt
}

路径分类

相对路径:相较于某个路径下,指明的路径
绝对路径:包含盘符在内的文件或文件目录的路径

相对路径的说明

idea中:使用JUint中的单元测试方法,相对路径为当前Module下。在main()测试中,相对路径为当前的Project下

Eclipse中:单元测试和main()测试,相对路径都是Project下

路径分割符:File.separator
在windows:\
在unix:/

常用方法

文件基本属性获取

public String getAbsolutePath(): 获取绝对路径

public String getPath(): 获取路径

public String getName(): 获取名称

public String getParent(): 获取上层文件目录路径,若无返回null

public String Length(): 获取文件长度(即字节),不能获取目录的长度

public String LastModified(): 获取最后一次的修改时间,毫秒值

文件遍历

public String[] list(): 获取指定目录下的所有文件或者文件目录的名称数组

public File[] listFiles(): 获取指定目录下的所有文件或者文件目录的File数组

@Test
public void test2(){
    File file1 = new File("./");
    File file2 = new File("/Users/jbb/java_project/pro01");

    System.out.println(file1.getAbsoluteFile());
    System.out.println(file1.getPath());
    System.out.println(file1.getName());
    System.out.println(file1.getParent());
    System.out.println(file1.length());
    System.out.println(new Date(file1.lastModified()));

    //遍历文件夹路径下文件-->输出文件的名
    String[] list = file1.list();
    for (String s : list) {
        System.out.println(s);
    }

    //遍历文件夹路径下文件-->输出完整的文件路径+文件名
    File[] files = file2.listFiles();
    for (File file : files) {
        System.out.println(file);
    }
}

文件重命名并移动

public boolean renameTo(File dest): 把文件重命名为指定的文件路径下

@Test
public void test3(){
    File file1 = new File("./hi2.txt");
    File file2 = new File("/Users/jbb/Documents/javaTest/hello2.txt");
    boolean renameTo = file1.renameTo(file2);
    System.out.println(renameTo);// 返回true表示操作成功,false表示失败
}

注:file1.renameTo(file2)为例:file1必须存在,file2不能存在(移动成功后file1不存在)

文件功能判断

public boolean isDirectory():判断是否是文件目录

public boolean isFile():判断是否是文件

public boolean exists():判断是否存在

public boolean canRead():判断是否可读

public boolean canWrite():判断是否可写

public boolean isHidden():判断是否是隐藏

    @Test
    public void test4(){
        File file1 = new File("./hi.txt");

        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isHidden());
    }

创建硬盘中对应的文件或文件目录

public boolean createNewFile(): 创建文件,若文件存在,则不创建,返回false

public boolean mkdir(): 创建文件目录,如果此文件目录存在就不创建了,如果此文件目录的上层目录不存在也不创建

public boolean mkdirs(): 创建文件目录,如果上层目录不存在,一并创建。

删除功能

public boolean delete(): 删除文件或者文件夹(此删除不走回收站)

@Test
public void test5() throws IOException {
    File file1 = new File("./hi.txt");
    if(!file1.exists()){
        file1.createNewFile();
        System.out.println("创建成功");
    }else {
        file1.delete();
        System.out.println("删除成功!");
    }

}

@Test
public void test6() throws IOException {
    //上一层目录不存在无法创建成功
    File file1 = new File("/Users/jbb/Documents/javaTest/IO2/io3");
    boolean mkdir = file1.mkdir();
    if (mkdir){
        System.out.println("mkdir 创建成功1");
    }

    //无论上一层目录是否存在,都会创建成功
    File file2 = new File("/Users/jbb/Documents/javaTest/IO2/io4");
    boolean mkdirs = file2.mkdirs();
    if(mkdirs){
        System.out.println("mkdirs 创建成功2");
    }
}

IO流原理及流的分类

流的分类

  • 按操作数据单位不同分为:字节流(8bit)、字符流(16bit)
  • 按数据流的流向(按程序的角度)不同分为:输入流、输出流
  • 按流的角色的不同分为:节点流、处理流

分类示意图:

流分类

IO流体系结构

IO流体系

常用的流

IO体系

节点流(文件流)

FileReader 和 FileWrite

读取文件内容到控制台中

@Test
public void testFileReader2() {
    FileReader fr = null;
    try {
        //1、获取读取文件
        File file = new File("hello.txt");
        //2、指定具体流
        fr = new FileReader(file);
        //3、读入的过程(使用char[]优化方式)
        char[] cbuf = new char[5];
        int len;
        while((len= fr.read(cbuf)) != -1){
            //方式一:
            //读取文件出错
            //for (int i = 0; i < cbuf.length; i++) {
            //    System.out.print(cbuf[i]);
            //}
            //for (int i = 0; i < len; i++) {
            //    System.out.print(cbuf[i]);
            //}

            //方式二
            //读取文件出错
            //String str = new String(cbuf);
            //表示每次写满cbuf的长度,最后没有满则逐个添加字符
            String str = new String(cbuf, 0, len);
            System.out.print(str);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        //4、关闭资源
        if(fr != null) {
            try {
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

说明:

1、read():返回读入的每一个字符,如果达到文件末尾,返回-1

2、异常处理:为保证流资源一定可以执行关闭操作,需要try-catch-finally处理

3、读入的文件一定要存在,否在就会报FileNotFoundException

文件写出到新的文件

@Test
public void testFileWrite() {
    FileWriter fr = null;
    try {
        //指明操作的文件
        File file = new File("hello1.txt");
        //确定具体的流
        fr = new FileWriter(file, true);
        //向文件写入内容
        fr.write("I'm a working\n");
        fr.write("It's very intersting");

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(fr != null){
            //资源关闭
            try {
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

说明:

1、输出操作,对应的File可以不存在,并不会报错

2、File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件

File对应的硬盘中的文件如果存在:

构造器:FileWriter(file, false) / FileWriter(file):就会对原文件进行覆盖

构造器:FileWriter(file, true):不会对原文件覆盖,而是在原文件的基础上追加内容

文件的读入写出操作,从scrFile完整复制到destFile

@Test
public void testFileReaderWrite() {
    FileReader fr = null;
    FileWriter fw = null;
    try {
        //操作的文件
        File srcFile = new File("hello.txt");
        File destFile = new File("hello2.txt");
        //具体的流操作
        fr = new FileReader(srcFile);
        fw = new FileWriter(destFile);

        //读入、写出操作
        char[] cbuf = new char[5];
        int len;
        
        //读取到char数组的字符的个数
        while ((len = fr.read(cbuf)) != -1){
            fw.write(cbuf, 0, len);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        //资源关闭
        try {
            if(fw != null)
                fw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            if (fr != null)
                fr.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

FileInputStream 和 FileOutputStream

使用字节流读入文本文件

@Test
public void FileInputStreamTest() {
    FileInputStream fis = null;
    try {
        //造文件
        File file = new File("hello.txt");
        //造流
        fis = new FileInputStream(file);
        //读入操作-->byte数组保存char字符,容易出乱码
        byte[] buffer = new byte[5];
        int len;
        while((len = fis.read(buffer)) != -1){
            String str = new String(buffer, 0, len);
            System.out.print(str);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(fis != null){
            //资源关闭
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

注:使用字节流处理文本文件可能会出现乱码

使用字节流处理非文本文件:复制图片

@Test
public void FileInputOutStreamTest() {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        File scrFile = new File("omnigraffle1.png");//源文件
        File destFile = new File("omnigraffle2.png");//目标文件

        fis = new FileInputStream(scrFile);
        fos = new FileOutputStream(destFile);

        byte[] buffer = new byte[5];
        int len;
        while((len = fis.read(buffer)) != -1){
            fos.write(buffer, 0, len);
        }
        System.out.println("复制成功");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(fos != null){
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

结论:

1、对于文本文件(.txt, .java, .c, .cpp ...),建议使用字符流处理(FileReader 和 FileWrite)

2、对于非文本文件(.jpg, .mp3, .mp4, .doc, .pdf),使用字节流处理(FileInputStream 和 FileOutputStream)

缓冲流(处理流之一)

作用:提供流的读入、写出操作,提高读写速度,原因是提供了一个缓冲区

private static int DEFAULT_BUFFER_SIZE = 8192;

BufferedInputStream 和 BufferedOutputStream

字节流的处理流:实现文件复制

@Test
public void testBufferedByte(){
    FileInputStream fis = null;
    FileOutputStream fos = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        //造文件
        File srcFile = new File("hello.txt");
        File destFile = new File("hello4.txt");

        //造流
        //文件流
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        //缓冲流
        bis = new BufferedInputStream(fis);
        bos = new BufferedOutputStream(fos);

        //复制过程实现-->字节读入到写出,不存在显式地打印输出,不会出现乱码问题
        byte[] buffer = new byte[5];
        int len;
        while((len = bis.read(buffer)) != -1){
            bos.write(buffer, 0 ,len);
            //刷新缓冲区
            bos.flush();
        }
        System.out.println("复制成功");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(bos != null){
            //关闭资源
            try {
                bos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(bis != null){
            try {
                bis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        //注:外层缓冲流关闭,内层字节流自动关闭
        //fos.close();
        //fis.close();
    }
}

BufferedReader 和 BufferedWrite

字符流的处理流:实现文本文件的复制

@Test
public void testBufferedChar(){
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        //指定文件和造流
        br = new BufferedReader(new FileReader(new File("hi.txt")));
        bw = new BufferedWriter(new FileWriter(new File("hi2.txt")));

        //文件复制过程
        //方式一:按每个char[] 读取
        //char[] cbuf = new char[10];
        //int len;
        //while((len = br.read(cbuf)) != -1){
        //    bw.write(cbuf, 0 ,len);
        //    bw.flush();
        //}
        //方式二:按每一行读取
        String data;
        while((data = br.readLine()) != null){
            //写出+换行
            //方法一:
            //bw.write(data + "\n");
            //方法二:
            bw.write(data);
            bw.newLine();//写完一行,新换一行

            bw.flush();
        }
        System.out.println("复制成功。");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(bw != null){
            //关闭资源
            try {
                bw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(br != null){
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

案例:词频统计,读一个文本文件内容,统计每个字符到一个文件中

//CountWord.java
public class CountWord {
    public static void main(String[] args) {
        FileReader fr = null;
        BufferedWriter bw = null;
        try {
            //map集合临时存储 “字符 = 数量”
            HashMap<Character, Integer> map = new HashMap<>();
            fr = new FileReader(new File("hi.txt"));
            bw = new BufferedWriter(new FileWriter(new File("hi_countWord.txt")));

            char[] cbuf = new char[5];
            int data;
            while((data = fr.read(cbuf)) != -1) {
                for (int i = 0; i < data; i++) {
                    char ch = (char) cbuf[i];
                    if (map.get(ch) == null) {
                        map.put(ch, 1);
                    } else {
                        map.put(ch, map.get(ch) + 1);
                    }
                }
            }
            //将map集合中的键值对写出到文件中
            Set<Map.Entry<Character, Integer>> entries = map.entrySet();
            for( Map.Entry<Character, Integer> entry: entries ) {
				//匹配key的值
                switch (entry.getKey()) {
                    case ' ':
                        bw.write("空格=" + entry.getValue());
                        break;
                    case '\n':
                        bw.write("换行=" + entry.getValue());
                        break;
                    case '\t':
                        bw.write("制表符=" + entry.getValue());
                        break;
                    case '\r':
                        bw.write("回车=" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                        break;
                }
                bw.newLine();//每写出一次,换行
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(fr != null){
                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

转换流(处理流之二)

转换流:属于字符流

InputStreamReader:将一个字节的输入流转换为字符的输入流

OutputStreamWriter:将一个字符输出流转换为字节的输出流

作用:提供字节流与字符流之间的转换

转换流实现示意图

转换流

实现字节的输入流到字符的输入流的转换:InputStreamReader

@Test
public void test1() throws IOException {
    File file = new File("hello.txt");
    FileInputStream fis = new FileInputStream(file);
    //使用系统默认的字符集
    //InputStreamReader isr = new InputStreamReader(fis);
    //参数2指定字符集-->根据文件保存时的字符集
    InputStreamReader isr = new InputStreamReader(fis, "utf-8");

    char[] cbuf = new char[5];
    int len;
    while((len = isr.read(cbuf)) != -1){
        String str = new String(cbuf, 0, len);
        System.out.print(str);
    }
    isr.close();
    fis.close();
}

综合使用:InputStreamReader、OutputStreamWriter

@Test
public void test2() throws IOException {
    File file1 = new File("hello.txt");
    File file2 = new File("hello_gbk.txt");

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

    InputStreamReader isr = new InputStreamReader(fis, "utf-8");
    OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");

    char[] cbuf = new char[5];
    int len;
    while((len = isr.read(cbuf)) != -1){
        osw.write(cbuf, 0, len);
        osw.flush();
    }

    osw.close();
    isr.close();
}

解码:字节、字节数组 --> 字符数组、字符串

编码:字符数组、字符串 --> 字节、字节数组

字符集:

ASCII:美国标准信息交换码,用一个字节的7位可以表示

ISO8859-1:拉丁码表、欧洲码表,用一个字节的8位表示

GB2312:中国的中文编码表,最多两个字节编码所有字符

GBK:中国的中文编码表升级版,融合更多的中文文字字符号,最多两个字节编码

Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示

UTF-8:变长的编码方式,可用1-4个字节来表示一个字符

标准输入、输出流

System.in:标准的输入流,默认从键盘输入

System.out:标准的输出流,默认从控制台输出

方法:setIn(InputStream is) / setOut(PrintStream ps):重新指定输入和输出的流

示例一:

/** 
  * 从键盘输入字符串,要求将读取到的整行字符串转换成大写输出。然后继续进行输入操作,
  * 直到当输入"e" 或者 "exit"时,退出程序
  *
  * 方法一:使用Scanner实现,调用next()返回一个字符串
  * 方式二:使用System.in实现, System.in --> 转换流 --> BufferedReader的readLine()
  */
@Test
public void test1(){

    BufferedReader br = null;
    try {
        InputStreamReader isr = new InputStreamReader(System.in);
        br = new BufferedReader(isr);
        while (true){
            System.out.println("请输入字符串:");
            String line = br.readLine();
            if("e".equalsIgnoreCase(line) || "exit".equalsIgnoreCase(line)){
                System.out.println("程序结束");
                break;
            }
            String toUpperCase = line.toUpperCase();
            System.out.println(toUpperCase);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(br != null){
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

示例二:从控制台输入字符串转换基本的数据类型(byte、short、boolean、float、double、int)

//MyInput.java
public class MyInput {

    public static String readStr() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        try {
            str = br.readLine();
        } catch (IOException e) {
            System.out.println(e);
        }
        return str;
    }

    public static byte nextByte(){
        return Byte.parseByte(readStr());
    }

    public static short nextShort(){
        return Short.parseShort(readStr());
    }

    public static boolean nextBoolean(){
        return Boolean.parseBoolean(readStr());
    }

    public static float nextFloat(){
        return Float.parseFloat(readStr());
    }

    public static double nextDouble(){
        return Double.parseDouble(readStr());
    }

    public static int nextInt(){
        return Integer.parseInt(readStr());
    }
}

打印流

PrintStream 和 PrintWriter

@Test
public void test3() {
    PrintStream ps = null;
    try {
        FileOutputStream fos = new FileOutputStream(new File("ASCII_char.txt"));
        //创建打印输出流,设置为自动刷新模式
        ps = new PrintStream(fos, true);
        if(ps != null){
            //把标准输出流(劫持控制台输出)改成写出文件
            System.setOut(ps);
        }

        for (int i = 0; i <= 255; i++) {
            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();
        }
    }
}

数据流

DataInputStream 和 DataOutputStream

作用:用于读取或写出基本数据类型的变量或字符串

数据流写出到data.txt

@Test
public void test4() throws IOException {
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File("data.txt")));
    dos.writeUTF("张三");
    dos.flush();//刷新操作,将数据保存到文件中
    dos.writeInt(19);
    dos.flush();
    dos.writeBoolean(true);
    dos.flush();

    dos.close();
}

数据流读入:将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中

@Test
public void test5() throws IOException {
    DataInputStream dis = new DataInputStream(new FileInputStream(new File("data.txt")));
    String name = dis.readUTF();
    int age = dis.readInt();
    boolean isMale = dis.readBoolean();
    System.out.println("name = " + name);
    System.out.println("age = " + age);
    System.out.println("isMale = " + isMale);

    dis.close();
}

注:读入的顺序要与写出的顺序一致,否在报错

对象流

ObjectInputStream 和 ObjectOutputStream

作用:用于存储和读取基本的数据类型数据或者对象的处理流

一个java对象要想实现序列化,要满足的要求:

1、需要实现接口(标识接口):Serializable

2、当前类提供一个全局常量:serialVersionUID

3、除了当前类需要实现Serializable接口外,还必须保证其内部所有属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)

序列化:将内存中java对象类型(基本数据类型)保存到硬盘文件中

实体类

//Person.java
public class Person implements Serializable {//实现接口Serializable
    private static final long serialVersionUID = 435686722343L;//提供serialVersionUID
    private String name;
    private Integer age;

    private Account acct;//内部引用

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name, Integer age, Account acct) {
        this.name = name;
        this.age = age;
        this.acct = acct;
    }

    public Account getAcct() {
        return acct;
    }

    public void setAcct(Account acct) {
        this.acct = acct;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", acct=" + acct +
                '}';
    }
}

class Account implements Serializable{//实现接口Serializable
    private static final long serialVersionUID = 435672234345L;//提供serialVersionUID
    private double balance;

    public Account(double balance) {
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "balance=" + balance +
                '}';
    }
}

测试

ObjectOutputStream写出文件

@Test
public void test1(){
    ObjectOutputStream oos = null;
    try {
        //造文件造对象流
        oos = new ObjectOutputStream(new FileOutputStream("data.dat"));
        //写出文件内容
        oos.writeObject(new String("这里是中国,请出示证件"));
        oos.flush();

        oos.writeObject(new Person("张三", 21));
        oos.flush();

        oos.writeObject(new Person("李四", 25, new Account(1999.99)));
        oos.flush();

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(oos != null){
            try {
                //关闭资源
                oos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

反序列化:从硬盘文件中的对象还原为内存的一个java对象,显示在控制台

ObjectInputStream读入内存

@Test
public void test2(){
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("data.dat"));
        Object obj = ois.readObject();
        String str = (String) obj;
        System.out.println(str);//这里是中国,请出示证件

        Object obj2 = ois.readObject();
        Person p = (Person) obj2;
        System.out.println(p);//Person{name='张三', age=21, acct=null}

        Object obj3 = ois.readObject();
        Person p2 = (Person) obj3;
        System.out.println(p2);//Person{name='李四', age=25, acct=Account{balance=1999.99}}

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

注:反序列化的时候,在序列化没有初始化的属性,输出的结果使用默认值填充,引用类型为null

随机存取文件流

1、RandomAccessFile直接继承java.lang.Object类,实现了DataInput和DataOutput接口,即包含read()和write()

2、RandomAccessFile既可以作为一个输出流,也可以作为输入流

3、如果RandomAccessFile作为输出流时,写出到文件如果不存在,则在执行过程中自动创建文件

​ 如果写出文件存在,则会对原有文件内容进行覆盖(默认情况下,从头覆盖)

RandomAccessFile访问模式:

r:以只读方式打开

rw:打开以便读取和写入

rwd:打开以便读取和写入,同步文件内容的更新

rws:打开以便读取和写入,同步文件内容和元素数据的更新

常用方法:

read() \ write() \ seek()

复制一个非文本文件

@Test
public void test1(){
    RandomAccessFile raf1 = null;
    RandomAccessFile raf2 = null;
    try {
        //造文件造流
        raf1 = new RandomAccessFile(new File("omnigraffle1.png"), "r");
        raf2 = new RandomAccessFile(new File("omni.png"), "rw");

        //读写过程
        byte[] buffer = new byte[1024];
        int len;
        while((len = raf1.read(buffer)) != -1){
            raf2.write(buffer, 0 ,len);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        //关闭资源
        if(raf2 != null){
            try {
                raf2.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(raf1 != null){
            try {
                raf1.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

使用RandomAccessFile实现插入效果

@Test
public void test4() throws IOException {
    RandomAccessFile raf1 = new RandomAccessFile(new File("hello.txt"), "rw");

    raf1.seek(5);
    //字节流数组临时储存角标5后面的字节
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[10];
    int len;
    while ((len = raf1.read(buffer)) != -1){
        //按字节写出保存
        baos.write(buffer, 0, len);
    }
    raf1.seek(5);
    raf1.write("opq".getBytes());
    //将字节数组转换为byte后写出raf1,解决乱码问题
    raf1.write(baos.toByteArray());

    raf1.close();
}

NIO.2中Path、Paths、Files类的使用

NIO概述

Java NIO(New IO,Non-Blocking IO)是java1.4版本开始引入的新的IO API,可以替代原来标准的IO。与原来版本的IO功能和目的一样,但使用方式完全不同。NIO支持面向缓冲区的(标准IO是面向流的)、基于通道的IO操作。NIO方便高效地进行文件的读写操作。

Java API中提供了两套NIO:一套是针对标准的输入输出NIO,另一套就是网络编程NIO

NIO.2是由NIO拓展来的

随着JDK7的发布,java对NIO进行了极大的扩展,增强了对文件处理和文件系统特性的支持,称它为NIO.2。

NIO.2新的变化

早期的java只提供了一个File类来访问文件系统,但File类的功能比较有限,所提供的方法性能也不高。而且,大多数方法在出错时仅返回失败,并不会提供异常信息。

NIO.2为了弥补这些不足,引入了Path接口,代表了一个平台无关的平台路径,描述了目录结构中文件的位置。Path可以看成是File类的升级版本,实际引用的资源也可以不存在。

获取IO操作对象的方式

//jdk1.7之前
import java.io.File           
File file = new File("index.html")

//jdk1.7之后
import java.nio.file.Path   
import.java.nio.file.Paths  
Path path = Paths.get("index.html")

NIO.2在java.nio.file包下还提供了Files,Paths工具类,Files包含了大量静态的工具方法来操作文件,Paths则包含了二个返回Path的静态工厂方法

Paths工具类

提供的静态方法get()方法用来获取Path对象:

//方式一
public static Path get(String first, String... more) {}

//方式二
public static Path get(URI uri) {}

Path接口

Path接口常用方法:

String toString():返回调用Path对象的字符串表示形式

boolean startWith(String path):判断是否以path路径结开始

boolean endsWith(String path):判断是否以path路径结束

boolean isAbsolute():判断是否是绝对路径

Path getParent():返回Path对象包含整个路径,不包含Path对象指定的文件路径

Path getRoot():返回调用Path对象的根路径

Path getFileName():返回与调用Path对象关联的文件名

int getNameCount():返回Path根目录后面元素的数量

Path getName(int idx):返回指定索引位置idx的路径名称

Path toAbsolutePath():作为绝对路径返回调用Path对象

Path resolve(Path p):合并二个路径,返回合并后的路径对应的Path对象

File toFile():将Path转化为File类的对像

Files工具类

用于操作文件或目录的工具类:

Path copy(Path src,Path dest,CopyOption...how):文件的复制

Path createDirectory(Path path,FileAttribute<?>...attr):创建一个目录

Path createFile(Path path,FileAttribute<?>...arr):创建一个文件

void delete(Path path):删除一个文件/目录,如果不存在,执行报错

void deleteifExists(Path path):Path对应的文件/目录如果存在,执行删除

Path move(Path src,Path dest,CopyOption..how):将src移动到dest位置

long size(Path path):返回path 指定文件的大小

Files常用方法:用于判断的

boolean isDirectory(Path path, LinkOption... options):判断文件是否是目录

boolean exists(Path path, LinkOption... options):判断文件是否存在

boolean isRegularFile(Path path, LinkOption... options):判断是否是文件

boolean isHidden(Path path):判断是否是隐藏文件

boolean isWritable(Path path):判断文件是否可写

boolean notExists(Path path, LinkOption... options):判断文件是否不存在

Files常用方法:用于操作内容

SeekableByteChannel newByteChannel(Path path, OpenOption... options):获取与指定文件的连接,options为打开方式

DirectoryStream<Path> newDirectoryStream(Path dir):打开path指定的目录

InputStream newInputStream(Path path, OpenOption... options):获取InputStream对象

OutputStream newOutputStream(Path path, OpenOption... options):获取OutputStream对象

Files类读入写出文件

static Path write(Path path, byte[] bytes, OpenOption...Options):写入文件

static byte[] readAllBytes(Path path):读取文件中的所有字节。

示例

//PathFilesTest.java
public class PathFilesTest {

    //创建文件或目录
    @Test
    public void createFileOrDir() throws IOException {
        Path path1 = Paths.get("/Users/jbb/Documents/javaTest/IO1");
        //创建新的目录-->IO1
        System.out.println(Files.createDirectory(path1));

        //创建多级目录-->IO2/test
        Path path2 = Paths.get("/Users/jbb/Documents/javaTest/IO1/test");
        System.out.println(Files.createDirectories(path2));

        //在指定目录下,创建文件
        Path path3 = Paths.get("/Users/jbb/Documents/javaTest/IO1", "test.txt");
        System.out.println(Files.createFile(path3));
    }

    //删除文件
    @Test
    public void deleteFile(){
        Path path1 = Paths.get("/Users/jbb/Documents/javaTest/IO1");
        try {
            Files.deleteIfExists(path1);//删除空的文件夹,成功返回true
            System.out.println("删除成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //拷贝文件
    @Test
    public void copyFile(){
        Path srcPath = Paths.get("/Users/jbb/Documents/javaTest/IO1/test.txt");
        Path destPath = Paths.get("/Users/jbb/Documents/javaTest/test_bak.txt");
        try {
            //StandardCopyOption.REPLACE_EXISTING(存在就替换) 
            // \ COPY_ATTRIBUTES(存在就拷贝为新的) \ ATOMIC_MOVE(作为原子文件操作执行移动)
            Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("拷贝成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //移动文件
    @Test
    public void moveFile(){
        Path srcPath = Paths.get("/Users/jbb/Documents/javaTest/IO1/test.txt");
        Path destPath = Paths.get("/Users/jbb/Documents/javaTest/test_move.txt");
        try {
            Files.move(srcPath, destPath,StandardCopyOption.REPLACE_EXISTING);
            System.out.println("移动成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //读取文件内容
    @Test
    public void readFromFile(){
        Path path = Paths.get("/Users/jbb/Documents/javaTest/hello.txt");
        byte[] bytes = new byte[0];
        try {
            //readAllBytes():读入指定文件所有的字节为一个字节数组
            bytes = Files.readAllBytes(path);
            String str = new String(bytes);
            System.out.println(str);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //向文件写入内容
    @Test
    public void writeFile(){
        Path path = Paths.get("/Users/jbb/Documents/javaTest/test_bak.txt");
        String str = "Hi, I'm Jom, 来自韩国!";
        try {
            Files.write(path,str.getBytes("utf-8"),StandardOpenOption.APPEND);
            System.out.println("写出成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //获取文件路径
    @Test
    public void getFilePath(){
        File file = new File("/Users/jbb/Documents/javaTest/");
        Path path1 = Paths.get("/Users/jbb/Documents", "javaTest");
        System.out.println(path1);// /Users/jbb/Documents/javaTest

        Path path2 = file.toPath();
        System.out.println(path2);// /Users/jbb/Documents/javaTest

        Path path3 = FileSystems.getDefault().getPath("/Users/jbb/Documents/javaTest/");
        System.out.println(path3);// /Users/jbb/Documents/javaTest
    }
}
posted @ 2022-10-04 21:32  Bingeone  阅读(50)  评论(0编辑  收藏  举报