Java实战开发篇-9 文件和流

一、简介

1.文件的概念:数据在磁盘的唯一最小描述,上层应用程序必须通过文件来操作磁盘上的数据
注:Java中的File不是真实文件
网络下载的数据(文本 图片 视频 音频)写入缓存,读取缓存中的数据需要流来实现
2.读写文件的步骤一般为
(1)创建文件、创建目录(文件夹)
(2)判断文件是不是存在(判断目录是否存在)
(3)写入数据
(4)删除文件、删除目录
3.写入、读取数据
Java中的File是没有具体读取和写入的方法,需要通过输入输出流来操作
输出流:内存-外部(硬盘,网络,设备)
输入流:外部-内存
4.数据的存储有两种
(1)字节形式:图片,音频,视频,exe,这些是以二进制形式存储的
(2)字符形式:文本
所以读取方式有所不同
字节形式用字节流,一次读取一个字节,InputStream/OutputStream
字符形式用字符流,一次读取一个字符(两个字节)Reader/Writer
输入输出流都是抽象类,所以我们需要使用输入输出流的具体实现类
字节输入输出流:FileInputStream/FileOutputStream
字符输入输出流:FileReader/FileWriter

二、字节流

类1——创建一个文件

class creatFile {
    public static void creatFile() {
        //关键字File,让file指向一个对应文件,需要文件名
        //new File并不会自动创建文件
        File file = new File("C:\\Users\\Administrator\\Desktop\\1.text");
        //判断文件或者目录是否存在
        if (!file.exists()) {
            //3.创建文件,捕获异常
        try {
            file.createNewFile();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }
            }
            }

类2——创建一个目录

class creatDir {
    public static void creatDir() {
        File file = new File("C:\\Users\\Administrator\\Desktop\\", "file");
        if (!file.exists()) {
        try {
            file.mkdir();
            } catch (NullPointerException e) {
            e.printStackTrace();
            }
            }
            }
            }

类3——删除文件

class deleteFile {
    File file = new File("C:\\Users\\Administrator\\Desktop\\", "1.text");
    public void deleteFile() {
        if (file.exists()) {
            file.delete();
         }
         }
         }

类4——判断是文件还是目录

class FileOperation {
    File file = new File("C:\\Users\\Administrator\\Desktop\\代码");
    public void operation() {
        if (file.isFile()) {
            System.out.println("是文件");
        }
        if (file.isDirectory()) {
            System.out.println("是目录");
        }
        }
        }

类5——查看当前文件的所有内容

class List {
    File file = new File("C:\\Users\\Administrator\\Desktop\\", "1.text");
    String[] fileNameList = file.list();
    public void List() {
        for (String name : fileNameList) {
            System.out.print(name);//输出所有列表的名称
        }
        }
        }

类6——过滤文件(按要求筛选文件)

class Choose {
    File file = new File("C:\\Users\\Administrator\\Desktop\\", "1.text");
    public void choose() {
        String[] chooseNameList = file.list(new FilenameFilter() {
                //筛选文件需要实现FilenameFilter类,这里使用匿名内部类减少代码量
            @Override
            public boolean accept(File dir, String name) {
                //如果返回true,当前文件会被选中
                //如果返回false,当前文件会被过滤掉
                File f = new File(dir, name);
                if (f.isDirectory()) {
                    return true;
                }
                return false;
            }
            });
            }
            }

类7——写入数据

class Write {
    String des = "C:\\Users\\Administrator\\Desktop\\";

    public static void WriteToFile(String des) {
        //1.准备数据
        String text = "Hello World";
        FileWriter fw = null;
        //2.判断是需要字符流还是字节流
        try {
            //3.写入数据
            fw = new FileWriter(des);
            fw.write(text);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }
            }

类8——复制字节型文件

class CopyChar {
    public static void CopyImageToFile(String src, String des) {
        //1.将图片读取到内存中
        //字节输入流FileInputStream
        //2.将内存中的数据写入到磁盘中
        //字节流 输出流 FileOutputStream
        //凡是实现了closeable接口的类,都可以在try()括号内部创建对象
        //当try代码块执行完毕或者有异常,系统自动close
        try (FileInputStream inf = new FileInputStream(src);
             FileOutputStream outf = new FileOutputStream(des)) {
            int b;
            //byte[] bytes = new byte[1024];操作一个字节数组,解决read()效率低的问题
            while (true) {
                b = inf.read();
                //read();方法是一个一个字节的读,当文件较大时,效率就会非常低
                //b = inf.read(byte);
                if (b == -1) {
                    break;
                }//当读取完毕后返回值默认为-1,操作字节数组时是一样的
                outf.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
        }

类9——复制字符型文件

class CopyText {
    public static void CopyTextToFile(String src, String des) {
        //复制字符和复制字节方法是完全一样的,只是关键字不一样
        try (FileReader inf = new FileReader(src);
             FileWriter outf = new FileWriter(des)) {
            int b;
            //byte[] bytes = new byte[1024];操作一个字符数组
            while (true) {
                b = inf.read();
                //b = inf.read(byte);
                if (b == -1) {
                    break;
                }
                outf.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
        }

三、处理流——缓冲流

缓冲输入流BufferedInputStream BufferedReader
缓冲输出流BufferedOutputStream BufferedWriter
虽然使用了处理流比较快,但是真正读取数据的是节点流
1.必须先创建节点流对象,将数据从磁盘读到内存缓冲区
2.将内存缓冲区的数据读到处理流对应的缓冲区
3.从处理流的缓冲区将数据读取到对应的地方
输入输出重定向——打印流(PrintStream)指定输入输出的位置(默认是输出到终端)

类1——用处理流复制字节

class BufferChar{
    public void Operation(String scr,String des){
        BufferedOutputStream bos = null;
        try {
            //创建缓冲输入流
            FileInputStream fis = new FileInputStream(scr);
            BufferedInputStream bis = new BufferedInputStream(fis);
            //创建缓冲输出流
            FileOutputStream fos = new FileOutputStream(des);
            bos = new BufferedOutputStream(fos);
            int b;
            while((b = bis.read())!= -1){
                bos.write(b);
            }
            bos.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }
            }

类2——用处理流复制字符

class BufferText{
    public void Operation(String scr,String des){
        BufferedWriter bw = null;
        try{
            //创建输入流
            FileInputStream fis = new FileInputStream(scr);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            //创建输出流
            FileOutputStream fos = new FileOutputStream(des);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);
            int b;
            while((b = br.read())!= -1){
                bw.write(b);
            }
            bw.flush();//当使用处理读取和输出时,需要调用flush()来刷新数据流
           }catch (Exception e){
            e.printStackTrace();
           }finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }

类3——重定向输入输出——在指定位置输出、在指定位置输入

class ReDirection{
    public void redirection_out(String des){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(des);
            PrintStream ps = new PrintStream(fos);//重定向输出,在指定位置输出
            System.setOut(ps);
            System.out.println("Hello World");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }
    public void redirection_in(String src){
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(src);
            Scanner scanner = new Scanner(fis);//重定向输入,在指定位置输入
            while (scanner.hasNext()){
                //把所有行的内容显示出来(默认只输出一行,所以写循环)
                System.out.println(scanner.next());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }
            }

四、对象处理

把一个对象通过文件的方式存储和读取

class Save_Read_Object{
    class Person implements Serializable{
        int age;
        String name;
        public Person(int age, String name) {
            this.age = age;
            this.name = name;
        }
        }
    public void saveobject(String des) {
        try {
            FileOutputStream fos = new FileOutputStream(des);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            Person p = new Person(18,"Jack");
            oos.writeObject(p);
        }catch (Exception e){
            e.printStackTrace();
        }
        }//将对象保存在指定文件里面
    public void readobject(String src){
        try{
            FileInputStream fis = new FileInputStream(src);
            ObjectInputStream ois = new ObjectInputStream(fis);
          Person p = (Person)ois.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }
        }//从指定文件里面读取对象
        }

五、RandomAccessFile类

当一个文件存在的时候,写入数据时会把原来的文件覆盖掉
如果不想发生此情况,需要使用RandomAccessFile

class RandromAccess{
    public void randomaccess(String src){
        try {
            RandomAccessFile raf = new RandomAccessFile(src,"rw");
            //有几种模式mode:r,rw,rws
            //r为只读,rw为可读写,rws为同时读写
        }catch (Exception e){
            e.printStackTrace();
        }
        }
        }

你可能感兴趣的:(Java实战开发篇-9 文件和流)