java-IO流

File类

java.io.File:文件夹和文件的对象表示。

   作用:操作文件和文件夹,可以对文件和文件夹进行增、删、重新命名操作。但是File类不能访问文件里面的内容,这个时候就需要IO流了。

  在java中要表示一个文件或文件夹的真实存在,那就必需要有一个File对象。但是java中有一个File对象,可能没有一个真实存在的文件或文件夹。

  File架构图,构造方法。实现了Serializable接口,告诉JVM是可序列化的。

File类的构造方法

代码演示

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

public class File_ {

    public static void main(String[] args)  {
        try {
            createFile4();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * File(File parent, String child)
     * 从父抽象路径名和子路径名字符串创建新的 File实例。
     */
    public static void createFile() throws IOException {
        String parent  = "E:\\";
        File parentFile = new File(parent);
        String child = "a.txt";
        File file = new File(parentFile,child);
        file.createNewFile();
    }

    /**
     * File(String pathname)
     * 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
     * @throws IOException
     */
    public static void createFile2() throws IOException {
        String pathname  = "E:\\b.txt";
        File file = new File(pathname);
        file.createNewFile();
    }

    /**
     * File(String parent, String child)
     * 从父路径名字符串和子路径名字符串创建新的 File实例。
     * @throws IOException
     */
    public static void createFile3() throws IOException {
        String parent  = "E:\\";
        String child = "c.txt";
        File file = new File(parent,child);
        file.createNewFile();
    }

    /**
     * File(URI uri)
     * 通过将给定的 file: URI转换为抽象路径名来创建新的 File实例。
     * 不给绝对路径,就是相对路径,会保存在项目路径下
     * @throws IOException
     */
    public static void createFile4() throws IOException {
        String uri = "d.txt";
        File file = new File(uri);
        file.createNewFile();
    }

}

 File类的常用方法

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

public class FileMethod {

    public static void main(String[] args) {

        try {
            System.out.println(mkdirs_());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return boolean
     * createNewFile()
     * 当且仅当具有该名称的文件尚不存在时,原子地创建一个由该抽象路径名命名的新的空文件。
     */
    public static boolean createNewFile_() throws IOException {
        String parent  = "E:\\";
        File parentFile = new File(parent);
        String child = "a.txt";
        File file = new File(parentFile,child);
        return file.createNewFile();
    }

    /**
     * boolean	delete()
     * 删除由此抽象路径名表示的文件或目录->只能删除文件或者空的文件夹。
     * @return
     * @throws IOException
     */
    public static boolean delete_() throws IOException {
        String filePath = "E:\\test";
        File file = new File(filePath);
        return file.delete();
    }

    /**
     * boolean	exists()
     * 测试此抽象路径名表示的文件或目录是否存在。
     * @return
     * @throws IOException
     */
    public static boolean exists_() throws IOException {
        String filePath = "E:\\test";
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * boolean	mkdir()
     * 创建由此抽象路径名命名的目录->只能创建单级目录。
     * @return
     * @throws IOException
     */
    public static boolean mkdir_() throws IOException {
        String filePath = "E:\\4\\abc";
        File file = new File(filePath);
        return file.mkdir();
    }

    /**
     * boolean	mkdirs()
     * 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录。
     * @return
     * @throws IOException
     */
    public static boolean mkdirs_() throws IOException {
        String filePath = "E:\\4\\abc\\a.txt";
        File file = new File(filePath);
        return file.mkdirs();
    }

}

IO流

真正懂IO流的优秀程序员每次在使用IO流之前都会明确分析如下四点:

1.明确要操作的数据是数据源还是数据本身(是读还是写)

2.明确要操作的设备上的数据是字节还是字符

3.明确数据所在的设备

4.明确是否需要额外功能

流是一种抽象概念,它代表了数据的无结构化传递。按照流的方式进行输入输出,数据被当成无结构的字节序或字符序列。IO流就是把数据通过流的方式输入输出。

流的输入输出是以程序为主说的,输入是从其它设备(磁盘)把数据输入到内存中,输出是把程序中的数据输出到其它设备中。

IO流分类

从三个维度给流分类

1.按流的方向:输入流(input)和输出流(output)

2.按照流的颗粒度:字节流和字符流

3.按照流的角色:节点流可以从一个特定的IO设备读写流,处理流也叫包装流,通过对已经存在的流进行连接或封装,通过封装后的流来读写数据。

IO流架构图

字节输入流(InputStream)架构图

 字节输出流(OutputStream)架构图

 字符输入流(Reader)架构图

 字符输出流(Writer)架构图

所有的文件都是以字节存储的

 我们必须明确一点的是,一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终为二进制数据。

字节输入流(InputStearm)

java.io.InputStearm是所有字节输入流的超类(父类),它定义了所有字节输入流的共性方法:

 InputStearm是抽象类不能实例化,我们用它的子类FileInputStearm用一下InputStearm的方法。

FileInputStearm类,文件输入流

常用构造方法:

// 根据File对象为参数创建对象
public FileInputStream(File file) throws FileNotFoundException{}

// 根据文件路径为参数创建对象
 public FileInputStream(String name) throws FileNotFoundException {
        // 还是实例化了一个File对象,在去调用根据File对象为参数创建对象的构造方法
        this(name != null ? new File(name) : null);
    }

接口方法读取文本文件:

中文会乱码,更加适合使用字符流。

    // 读取文件内容-单个字节
    public static void read() throws IOException {
        FileInputStream inputStream = new FileInputStream("E:\\c.txt");
        int read = 0;
        // read()方法,从输入流中读取数据,读取输入流中的下一个字节,如果没有数据返回-1
        while ((read = inputStream.read()) != -1){
            System.out.print((char)read);
        }
        // 关闭流
        inputStream.close();
    }

    // 读取文件内容-字节数组
    public static void read1() throws IOException {
        FileInputStream inputStream = new FileInputStream("E:\\c.txt");
        byte[] bytes = new byte[3];
        int readLeng = 0;
        // read(byte[] b)方法,一次读取一个字节数组,,如果没有数据返回-1
        while ((readLeng = inputStream.read(bytes)) != -1){
            System.out.println(new String(bytes,0,readLeng));
        }
        // 关闭流
        inputStream.close();
    }

字节输出流(OutputStearm)

所有字节输出流的超类(父类),定义了所有输出流的共性方法。

FileOutputStearm类,文件输出流

构造方法源码分析:

 /**
     * 通过文件路径创建对象
     * @param name 文件路径
     * @throws FileNotFoundException
     */
    public FileOutputStream(String name) throws FileNotFoundException {
        // 调用自己的构造方法,第二个参数默认false
        this(name != null ? new File(name) : null, false);
    }

    /**
     * 通过文件路径创建对象,是否从文件末尾拼接
     * @param name 文件路径
     * @param append 是否从文件末尾拼接,false会覆盖原文件内容
     * @throws FileNotFoundException
     */
    public FileOutputStream(String name, boolean append)throws FileNotFoundException {
        this(name != null ? new File(name) : null, append);
    }

    /**
     * 通过File对象创建对象
     * @param file 文件对象
     * @throws FileNotFoundException
     */
    public FileOutputStream(File file) throws FileNotFoundException {
        this(file, false);
    }

    /**
     * 上面所有的构造方法最后都还是走的这个构造方法
     * 通过文件创建对象,是否从文件末尾拼接
     * @param file 文件对象
     * @param append 是否从文件末尾拼接,false会覆盖原文件内容
     * @throws FileNotFoundException
     */
    public FileOutputStream(File file, boolean append)
            throws FileNotFoundException
    {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        this.fd = new FileDescriptor();
        fd.attach(this);
        this.append = append;
        this.path = name;

        open(name, append);
    }

接口方法写入内容到文本:

 /**
     * 写入字符到文本
     */
    public static void writer() throws IOException {
        // 通过文件路径创建对象 ,如果没有这个文件会创建一个新的文件
        FileOutputStream outputStream = new FileOutputStream("E:\\c.txt");
        // 写入字符到文件
        outputStream.write('徐');
        outputStream.flush();
    }

    /**
     * 写入字符数组到文本
     */
    public static void writer1() throws IOException {
        // 通过文件路径创建对象,第二个参数是否在文件后面追加
        FileOutputStream outputStream = new FileOutputStream("E:\\c.txt",true);
        String str = "sldjfs;adfjsld你好";
        // 写入字符数组到文本
        outputStream.write(str.getBytes());
        outputStream.flush();
    }

    /**
     * 指定写入字符数组的位置
     */
    public static void writer2() throws IOException {
        // 通过文件路径创建对象,第二个参数是否在文件后面追加
        FileOutputStream outputStream = new FileOutputStream("E:\\c.txt");
        String str = "sldjfs;adfjsld你好";
        // 指定写入字符数组的位置,从第二个开始,总共六个字符
        outputStream.write(str.getBytes(),2,6);
        outputStream.flush();
    }

结合输入流和输出流复制文件:

    /**
     * 拷贝文件
     */
    public static void copyFile() throws IOException {
       FileInputStream inputStream = new FileInputStream("E:\\111.jpg");
        FileOutputStream outputStream = new FileOutputStream("E:\\222.jpg");
       byte[] bytes = new byte[4];
       int readLeng = 0;
       while ((readLeng = inputStream.read(bytes)) != -1){
           outputStream.write(bytes,0,readLeng);
       }
       outputStream.close();
       inputStream.close();
    }

字符流

Reader字符输入流

FileReader类

// 继承了转换流InputStreamReader
public class FileReader extends InputStreamReader {


      /**
    * 三个构造方法都是调用了父类的构造方法,而且参数是字节输入流的实现类
    */
    public FileReader(String fileName) throws FileNotFoundException {
        super(new FileInputStream(fileName));
    }


    public FileReader(File file) throws FileNotFoundException {
        super(new FileInputStream(file));
    }

   
    public FileReader(FileDescriptor fd) {
        super(new FileInputStream(fd));
    }

}

FileReader读取文件中的内容演示:

   /**
     * 读取单个字符演示
     */
    public static void read(){
        try {
            FileReader reader = new FileReader("E:\\c.txt");
            int read = 0;
            // read()方法读取单个字符,返回下一个字符的字节码,如果下一个为空返回-1
            while ((read = reader.read())!= -1){
                System.out.print((char) read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 演示读取多个字节
     */
    public static void read1(){
        try {
            FileReader reader = new FileReader("E:\\c.txt");
            char[] chars = new char[8];
            int readLeng = 0;
            // read(char[] chars)方法一次读取一个字符数组,返回读取到的长度,如果返回值是-1代表已经读完
            while ((readLeng = reader.read(chars))!= -1){
                System.out.println(new String(chars,0,readLeng));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Writer字符输出流

public static void writer(){
        FileWriter writer = null;
        try {
            writer = new FileWriter("E:\\c.txt");
            writer.write("dfagdf奇莱柘城");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值