Java笔记之IO流(二十六)

一、基本介绍

1.基本概念

:数据在数据源(文件)和程序(内存)之间经历的路径
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径

2.常用文件操作

序号操作基本格式
1根据路径构建一个File对象new File(String pathname)
2根据父目录文件+子路径构建new File(File parent,String child)
3根据父目录+子路径构建new File(String parent,String child)
4获取文件大小file.length()
5获取文件名file.getName()
6获取文件绝对路径file.getAbsolutePath()
7获取文件的父Filefile.getParent()
8判断是不是文件file.isFile()
9判断是不是目录file.isDirectory()
10判断文件是否存在file.exists()
11创建一级目录,返回值为布尔file.mkdir()
12创建多级目录,返回值为布尔file.mkdirs()
13删除空目录或文件file.delete()

目录本质也是文件,一种特殊的文件

import java.io.File;
import java.io.IOException;

public class test {
    public static void main(String[] args) throws InterruptedException {
        //操作1
        File file1 = new File("F:\\test1.txt");
        try {
            file1.createNewFile();
            System.out.println("文件1创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //操作2
        File file2 = new File("F:\\","test2.txt");
        try {
            file2.createNewFile();
            System.out.println("文件2创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //操作3
        File file3 = new File("F:/","test3.txt");
        try {
            file3.createNewFile();
            System.out.println("文件3创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //操作4-10
        System.out.println("test1.txt "+file1.length());
        System.out.println("test1.txt "+file1.getName());
        System.out.println("test1.txt "+file1.getAbsolutePath());
        System.out.println("test1.txt "+file1.getParent());
        System.out.println("test1.txt "+file1.isFile());
        System.out.println("test1.txt "+file1.isDirectory());
        System.out.println("test1.txt "+file1.exists());

        //操作11-13
        File file4 = new File("F:\\Test");
        System.out.println(file4.mkdir());
        System.out.println(file4.exists());

        File file5 = new File("F:\\Test1\\Demo");
        System.out.println(file5.mkdirs());
    }
}

二、IO流

1.基本概念

I/O:即是Input和Output的缩写,I/O技术是非常实用的技术,用于处理数据的传输。如读写文件,网络通讯等。
Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行。
java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据。

注意:文件流使用完以后,要记得关闭文件流,释放资源

IO流的分类

  1. 按操作数据单位分为:字节流(如:二进制文件)和字符流(如:文本文件)
  2. 按数据流的流向分为:输入流和输出流
  3. 按流的角色的不同分为:节点流、处理流和包装流
抽象基类字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter

2.IO流常用的类

InputStream:直接输入流,抽象类是所有字节输入流的超类,下面是InputStream常用的子类

  1. FileInputStream:文件输入流
  2. BufferedInputStream:缓冲字节输入流
  3. ObjectInputStream:对象字节输入流

OutputStream:直接输出流,抽象类是所有字节输出流的超类,下面是OutputStream常用的子类

  1. FileOutputStream:文件输出流
  2. BufferedOutputStream:缓冲字节输出流
  3. ObjectOutputStream:对象字节输出流

三、FileInputStream和FileOutputStream

1.FileInputStream

FileInputStream: 即文件输入流,从文件系统中的某个文件中获得输入字节,方法使用如下图,具体详细的使用说明请看API

在这里插入图片描述

举例说明:对一个文件进行读取,并输出在控制台

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

public class test {
    public static void main(String[] args) throws InterruptedException {
        FileInputStream();
        System.out.println();
        FileInputStream1();
    }

    /**
     * 读取指定路径文件的内容,
     * 使用read方法是一个字节一个字节的读取,效率比较低
     */
    public static void FileInputStream(){
        String Path = "F:\\test.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(Path);
            //read()方法,如果到达文件末尾则返回-1,表示读取完毕
            while ((readData = fileInputStream.read()) != -1){
                System.out.print((char)readData);   //转换为char显示
            }
        } catch (IOException e) {
            //原本异常为FileNotFoundException,这里设置为IOException,为扩大异常范围
            e.printStackTrace();
        }finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用read(byte[] b)方法,最多b.length个字节的数据读入一个byte数组中,效率比较高
     */
    public static void FileInputStream1(){
        String Path = "F:\\test.txt";
        int readlen = 0;
        FileInputStream fileInputStream = null;
        byte[] bytes = new byte[8]; //一次读取8个字节
        try {
            fileInputStream = new FileInputStream(Path);
            //read(byte[] b)方法,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。
            //如果读取正常,返回实际读取的字节数
            while ((readlen = fileInputStream.read(bytes)) != -1){
                System.out.print(new String(bytes,0,readlen));   //转换为char显示
            }
        } catch (IOException e) {
            //原本异常为FileNotFoundException,这里设置为IOException,为扩大异常范围
            e.printStackTrace();
        }finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.FileOutputStream

FileOutputStream: 即文件输出流,是用于将数据写入 File 或 FileDescriptor 的输出流。

在这里插入图片描述

举例说明:对一个文件进行写入数据,如果没有则创建

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

public class test {
    public static void main(String[] args) throws InterruptedException {
        FileOutputStream();
//        FileOutputStream1();
//        FileOutputStream2();
    }

    /**
     * 将数据写到文件中,如果没有则创建
     * 写入一个字节
     * new FileOutputStream(filePath)会对原来的内容进行覆盖
     */
    public static void FileOutputStream(){
        String Path = "F:\\test1.txt";
        FileOutputStream fileOutputStream = null;
        try {
            //写入一个字节
            fileOutputStream = new FileOutputStream(Path);
            fileOutputStream.write('J');
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将数据写到文件中,如果没有则创建
     * 写入多个字节
     * new FileOutputStream(filePath)会对原来的内容进行覆盖
     */
    public static void FileOutputStream1(){
        String Path = "F:\\test1.txt";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(Path);
            //写入多个字节
            String s = "java";
            //getBytes() 可以把字符串转换为字符数组
            fileOutputStream.write(s.getBytes(),0,s.length());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将数据写到文件中,如果没有则创建
     * 写入多个字节,进行内容追加
     * new FileOutputStream(filePath,true)会对原来的内容进行追加
     */
    public static void FileOutputStream2(){
        String Path = "F:\\test1.txt";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(Path,true);
            String s = " scala";
            //getBytes() 可以把字符串转换为字符数组
            fileOutputStream.write(s.getBytes(),0,s.length());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.综合小案例-文件复制

将F盘下的java.jpeg图片复制为java2.jpeg

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

public class test {
    public static void main(String[] args) throws InterruptedException {
        String Path = "F:\\java.jpeg";
        String newPath = "F:\\java2.jpeg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(Path);
            fileOutputStream = new FileOutputStream(newPath);

            //定义一个数据,进行多个字节读取,提供效率
            byte[] bytes = new byte[1024];
            int readlen = 0;
            while ((readlen = fileInputStream.read(bytes)) != -1 ){
                //注意:这里复制的是图片,一定要用write(byte[] b, int off, int len),而不能用write(byte[] b),否则写入的就不是以前的图片了
                fileOutputStream.write(bytes,0,readlen);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
                if (fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

四、FileReader和FileWriter

1.FileReader

常用操作

序号基本格式操作
1new FileReader(File/String)构造器
2read()每次读取单个字符,返回该字符,如果到文件末尾返回-1
3read(char[])批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1
4new String(char[])将char[]转换成String
5new String(char[],off,len)将char[]的指定部分转换成String

快速入门
要求:使用FileReader从文本文件中读取内容,并显示

import java.io.FileReader;
import java.io.IOException;

public class test {
    public static void main(String[] args) throws InterruptedException {
//        FileReader();
        FileReader1();
    }

    /**
     * 单字符读取
     */
    public static void FileReader(){
        String path = "F:\\test.txt";
        FileReader fileReader = null;
        int data = 0;
        try {
            fileReader = new FileReader(path);
            while ((data = fileReader.read()) != -1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 批量读取多个字符到数组
     */
    public static void FileReader1(){
        String path = "F:\\test.txt";
        FileReader fileReader = null;
        char[] chars= new char[8];
        int readlen = 0;
        try {
            fileReader = new FileReader(path);
            while ((readlen = fileReader.read(chars)) != -1){
                System.out.print(new String(chars,0,readlen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

显示如下:
在这里插入图片描述

2.FileWriter

常用操作

序号基本格式操作
1new FileWriter(File/String)覆盖模式,相当于流的指针在首段
2new FileWriter(File/String,true)追加模式,相当于流的指针在尾端
3write(int)写入单个字符
4write(char[])写入指定数组
5write(char[],off,len)写入指定数组的指定部分
6write(String)写入整个字符串
7write(String,off,len)写入字符串的指定部分

相关API:String类:toCharArray:将String转换成char[]
注意:
FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件

快速入门
要求:使用不同格式write,向文件中写入数据

import java.io.FileWriter;
import java.io.IOException;

public class test {
    public static void main(String[] args) throws InterruptedException {
//        FileWriter();
//        FileWriter1();
//        FileWriter2();
//        FileWriter3();
        FileWriter4();
    }

    /**
     * 写入单个字符
     */
    public static void FileWriter(){
        String path = "F:\\test1.txt";
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(path);  //覆盖的模式
            fileWriter.write('H');
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 写入指定数组
     */
    public static void FileWriter1(){
        String path = "F:\\test1.txt";
        FileWriter fileWriter = null;
        char[] chars = {'a','b','c'};
        try {
            fileWriter = new FileWriter(path);  //覆盖的模式
            fileWriter.write(chars);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 写入指定数组的指定部分
     */
    public static void FileWriter2(){
        String path = "F:\\test1.txt";
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(path);  //覆盖的模式
            fileWriter.write("java你好".toCharArray(),0,5);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 写入整个字符串
     */
    public static void FileWriter3(){
        String path = "F:\\test1.txt";
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(path);  //覆盖的模式
            fileWriter.write("java你好,我是scala");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 写入字符串的指定部分
     */
    public static void FileWriter4(){
        String path = "F:\\test1.txt";
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(path);  //覆盖的模式
            fileWriter.write("我是java",0,2);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王博1999

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值