Java IO 相关复习基础笔记

2018-09-26  本文已影响22人  吾乃韩小呆

一、文件 File 类相关知识点整理

1、File 基本概念及操作

1)、概念:

文件和目录(文件夹)的路径名的抽象表示形式,具体存在与否,取决于具体操作。

2)、构造方法:

File(String pathname )根据路径得到 File 对象
File(String parent,String child)根据目录和文件(文件、目录)得到File对象
File(File parent,String child)根据一个父文件和文件(文件、目录)得到 File 对象
File(Uri uri)根据 uri 得到File对象

3)、常用方法

创建方法
public boolean createNewFile 在目录下创建文件;
public boolean mkdir()在目录下创建文件夹,存在就不创建,不存在就创建;
public boolean mkdirs 同时创建层级文件夹;
删除方法
public bollean delete() 删除文件或者文件夹;
Java 的删除不走回收站
重命名
public boolean renameTo(File file) 若路径名称相同则为重命名,否则为 剪切功能。
判断功能
public boolean isDirectory判断是否为路径
public boolean isFile判断是否为文件
public boolean exists判断是否存在
public boolean canRead()判断是否可读
public boolean canWrite()判断是否可写
public boolean isHidden()判断是否隐藏
获取方法
public String getAbsolutePath() 获取文件绝对路径
public String getPath()获取相对路径
public String getName()获取名称
public String length()获取文件长度
public String lastModified()获取文件最后一次修改时间。
超级获取
public String[ ] list()获取指定文件路径下所有文件名称的数组;
public File[ ] listFiles()获取指定文件路径下所有 文件对象 的数组;
public String [ ] list(FilenameFilter filter) 文件名称过滤器;
public File[ ] listFile(FilenameFilter filter) 文件名称过滤器。

二、递归

1、基础知识

定义:方法定义中调用方法本身
1)、Math.Max(Math.Max(0,8),10);被称之为方法嵌套调用,不是递归;
2)、 递归 != 死循环;
3)、递归次数不可过多,过多导致内存溢出
4)、构造方法不可进行递归使用。

递归的案例:

public class Main {

    public static void main(String[] args) {

        System.out.println(test(6));
    }

    private static int test(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n * test(n - 1);
        }
    }
}

取一个目录下所有的文件绝对路径:

import java.io.File;

public class Main {

    public static void main(String[] args) {

        File file = new File("F:\\java视频\\javaSE\\day01\\code\\代码\\HelloWorld案例");

        getFilePath(file);
    }

    private static void getFilePath(File file) {

        File[] files = file.listFiles();

        assert files != null;
        for (File file1 : files) {
            if (file1.isDirectory()) {
                getFilePath(file);
            } else {
                if ((file1.getName().endsWith(".java"))) {
                    System.out.println(file1.getAbsoluteFile());
                }
            }
        }
    }
}

三、Io流相关---->字节流

1、基础常识:

字符流:方便文本操作产生的;

字节流:非文本操作使用,只要是使用记事本打开无法读懂的就使用字节流进行操作(输入\输出)。

字节输入流 读取数据 InputStream 抽象类
字节输出流 写入数据 OutputStream 抽象类

字符输入流 读取数据 Reader
字符输出流 写入数据 Writer

2、基本的方法使用

1)、FileOutputStream 常用方法(构造方法+普通方法)

FileOutputStream (File file)
FileOutputStream(String name)
write(int b);写一个字节
write(Byte [ ] byte);写入一个字节数组
write(Byte [ ] byte,int off,int len ); 写入字节数组一部分
close(); 释放IO流资源

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream("test.txt");
            fos.write("hello java".getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行效果


FileOutputStream 效果
2)、实现数据换行

windows:\r\n
Linux:\n
Mac:\r

3)、追加写入

使用两个参数的构造方法
FileOutputStream(File file , boolean append); 可以进行追加写入

4)、FileInputStream 常用方法(构造方法+普通方法)

FileInputStream(File file);
FileInputStream(String name);
read();读取数据 当读完,则返回值为-1
close();关闭对象

import java.io.FileInputStream;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("test.txt");
            int test;
            while ((test = fis.read()) != -1) {
                System.out.print((char) test);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
使用样例

5)、一次读取一个字节数组

该方式大大的提高了读取效率

 private static void outputTest() {
        FileInputStream fis = null;
        //创造读取空间,每次读取1024字节
        byte[] byes = new byte[1024];
        int len;
        try {
            fis = new FileInputStream("D:\\test\\PicTest\\app\\src\\main\\java\\com\\example\\hxd\\pictest\\getPhotoFromPhotoAlbum.java");
            while ((len = fis.read(byes)) != -1) {
                System.out.print(new String(byes, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

6)、字节缓冲流

BufferedOutputStream 带缓冲区的 字节输出流
BufferedInputStream 带缓冲区的字节输入流

构造方法可以指定缓冲区的大小,一般来说默认的缓冲区即可够用;

//创建高效缓冲字节流
        BufferedInputStream bis = null;
        //创建缓冲区
        byte[] bytes = new byte[1024];
        try {
            bis = new BufferedInputStream(new FileInputStream("D:\\test\\PicTest\\app\\src\\main\\java\\com\\example\\hxd\\pictest\\getPhotoFromPhotoAlbum.java"));
            int bye;
            while ((bye = bis.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, bye));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

7)、使用四种方式完成,视频复制;

代码中展示了复制效率:

import java.io.*;

public class Main {

    public static void main(String[] args) {

        long a = System.currentTimeMillis();
        //        copyTest1("F:\\java视频\\javaSE\\day21-IO\\avi\\21.32_day21总结.avi", "D:\\test1.mp4");
        //        copyTest2("F:\\java视频\\javaSE\\day21-IO\\avi\\21.32_day21总结.avi", "D:\\test2.mp4");
        //        copyTest3("F:\\java视频\\javaSE\\day21-IO\\avi\\21.32_day21总结.avi", "D:\\test3.mp4");
        copyTest4("F:\\java视频\\javaSE\\day21-IO\\avi\\21.32_day21总结.avi", "D:\\test4.mp4");
        long b = System.currentTimeMillis();
        System.out.println("copyTest4 复制耗时: " + (b - a) + " 毫秒");
    }

    //copyTest1复制耗时: 134108 毫秒
    private static void copyTest1(String input, String output) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        int b;
        try {
            fis = new FileInputStream(input);
            fos = new FileOutputStream(output);
            while ((b = fis.read()) != -1) {
                fos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeInputOrOutput(fos, fis);

        }

    }

    //copyTest2复制耗时: 199 毫秒
    private static void copyTest2(String input, String output) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        byte[] bytes = new byte[1024];
        int b;
        try {
            fis = new FileInputStream(input);
            fos = new FileOutputStream(output);
            while ((b = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeInputOrOutput(fos, fis);
        }
    }


    //copyTest3复制耗时: 688 毫秒
    private static void copyTest3(String input, String output) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        int b;
        try {
            bis = new BufferedInputStream(new FileInputStream(input));
            bos = new BufferedOutputStream(new FileOutputStream(output));

            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeOutputOrInput(bis, bos);
        }
    }

    //copyTest4 复制耗时: 51 毫秒
    private static void copyTest4(String input, String output) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        byte[] bytes = new byte[1024];
        int b;
        try {
            bis = new BufferedInputStream(new FileInputStream(input));
            bos = new BufferedOutputStream(new FileOutputStream(output));
            while ((b = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeOutputOrInput(bis, bos);
        }
    }
//关闭流
    private static void closeInputOrOutput(FileOutputStream fos, FileInputStream fis) {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            System.out.println(e.toString());
        }

    }

//关闭流
    private static void closeOutputOrInput(BufferedInputStream bis, BufferedOutputStream bos) {
        try {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }
}

四、IO流相关--->字符流

1、OutputStreamWriter 相关

1)、构造方法

OutputStreamWriter(OutputStream out);字符流 根据默认编码将字节流转换为字符流

字符流=字节流+编码表;

OutputStreamWriter(OutputStream out,String charsetName);根据指定的编码将字节流转换为字符流

代码演示:
未进行指定编码格式

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Main {

    public static void main(String[] args) {
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(new FileOutputStream("test.txt"));
            osw.write("我爱Java和Android");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

指定编码格式(UTF-8):

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class Main {

    public static void main(String[] args) {
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(new FileOutputStream("test.txt"), StandardCharsets.UTF_8);
            osw.write("我爱Java和Android");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

注意一点,用什么格式保存的,就要用什么格式打开,否则会产生乱码。

2)、其他重要方法

public void write(int c)写入单个字符
public void write(char [ ] cbuf)写一个字符数组
public void write(char [ ] cbuf,int off,int len)写一个字符数组内的一部分 off 表示开始写的位置,len表示写的长度
public void write(String str)写一个字符串
public void write(String str, int off,int len)写一个字符串的一部分 off 表示开始写的位置,len表示写的长度
public void flush()刷新缓冲区,一般大量写入的时候才会调用。

注意:flush()方法和close()方法的区别?

flush();方法只是刷新缓冲区,方法之后仍然可以继续写入。

close();方法是关闭流,关闭之前进行缓存区的刷新。方法执行之后不可再进行写入操作。

2、InputStreamReader 使用

InputStreamReader (InputStream is);默认编码读取数据
InputStreamReader(InputStream is,String charsetName )指定编码格式读取数据
public int read()一次读取一个字符
public int read(char [ ] chuf )一次读取一个字符数组

指定编码格式读取数据(UTF-8)

import java.io.*;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        InputStreamReader isr = null;
        int ch;
        try {
            isr = new InputStreamReader(new FileInputStream("test.txt"), StandardCharsets.UTF_8);
            while ((ch = isr.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

甚记:输出和输入的编码格式 一定要相同,否则乱码。

3、FileWriter 与 FileReader

代码展示:

import java.io.*;

public class Main {
    public static void main(String[] args) {
        FileReader fr = null;
        FileWriter fw = null;

        try {
            fr = new FileReader("test.txt");
            fw = new FileWriter("a.txt");
            char[] chars = new char[1024];
            int len;

            while ((len = fr.read(chars)) != -1) {
                fw.write(chars, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                System.out.println(e.toString());
            }

        }
    }
}

这两个子类,类似于字节流的FileInputStream 和 FileOutputStream

4、字符缓冲流 BufferedWriter 和 BufferedReader

1)、简单使用

代码展示:

import java.io.*;

public class Main {
    public static void main(String[] args) {

        BufferedReader br = null;
        BufferedWriter bw = null;
        char[] chars = new char[1024];
        int len;
        try {
            br = new BufferedReader(new FileReader("F:\\java视频\\javaSE\\day22-IO\\avi\\22.25_day22总结.avi"));
            bw = new BufferedWriter(new FileWriter("test.avi"));
            while ((len = br.read(chars)) != -1) {
                bw.write(chars, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

不要用字符流去复制视频,,,复制完的就不能看了,2333.

2)、BufferedWriter 的高级使用

public void readLine()一次读取一行
public void newLine()自动换行
public void flush()刷新缓冲区

外加一个 writer()方法,三个方法连写。

总结:


IO流总结

四、牛刀小试(输入输出流使用)

1、将集合内数据存储到文件内

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        list.add("f");
        list.add("g");
        list.add("h");
        list.add("i");
        list.add("g");
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter("test.txt"));
            for (String array : list) {
                bw.write(array);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2、转移文件

import java.io.*;

public class Main {
    public static void main(String[] args) {
        //目标文件
        File startFile = new File("E:\\copy");
        //目标地点
        File endFile = new File("D:\\copyTest");
        if (!endFile.exists()) {
            endFile.mkdir();
        }
        //获取文件对象
        File[] files = startFile.listFiles();

        //遍历复制
        assert files != null;
        for (File file : files) {
            if (file.isFile()) {
                String name = file.getName();
                File newFile = new File(endFile, name);
                copyToNewFile(newFile, file);
            }
        }
        System.out.println("复制完成");
    }

    //具体流操作
    private static void copyToNewFile(File newFile, File file) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        byte[] bytes = new byte[1024];
        int by;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream(newFile));
            while ((by = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, by);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

六、其它流

1、数据操作流(操作基本类型数据的流)

DataInputStream
DataOutputStream

2、内存操作流

BateArrayInputStream
BateArrayOutputStream

CharArrayReader
CharArrayWriter

StringReader
StringWriter

3、打印流(字节打印流、字符打印流)

只要进行输出操作,输入操作还是使用字符流进行操作

PrintWriter

4、随机访问流

5、合并流

将多个输入文件写入到同一个文件内

SequenceInputStream(InputStream s1,InputStream s2);

SequenceInputStream(Enumeration<?
extends InputStream> e)

上一篇下一篇

猜你喜欢

热点阅读