[Java] File class and IO stream based on Java

table of Contents

File class

1. Construction method

2. Common methods

3. Judgment method

4. Create a delete method

5. Method of traversing directory

IO style

1. Byte stream

      1.1, byte output stream OutputStream

      1.1.1, byte output stream subclass FileOutputStream

     1.2, the input stream parent class InputStream

     1.2.1. Input stream subclass FileInputStream

2. Character stream

      2.1, Character input stream parent class Reader

     2.1.2, FileReader class

     2.2. Character output stream parent class Writer

     2.2.1, FileWriter class


File class

        The File class should be the translation "file class". The class used for file operations. File represents the abstract path of a file or folder . Since it is an abstract path, of course this path can exist or not. The File class has the following construction methods:

1. Construction method

File class construction method
method Description
public File(String pathname)

Create a File object given the path name

public File(String parent,Stirng child) Create a File object given the parent path and the child path
public File(File parent,String child) Create a File object given the File type of the parent path and the child path
import java.io.File;
//在java语言中 ""里面的\必须写成\\
//   \本身是转义字符的意思
public class Test01 {
    public static void main(String[] args) {
        //File的构造方法
        //public File(String pathname)

        //给定路径名称创建File对象
        File f = new File("C:\\Users\\jin\\Desktop\\day10");
        //File f = new File("C:/Users/jin/Desktop/day10");
        System.out.println(f);
        //public File(String parent, String child)

        //给定父路径和子路径创建File对象
        //File f2 = new File("C:\\Users\\jin\\Desktop","day10");
        File f2 = new File("C:\\Users\\jin","Desktop\\day10");
        System.out.println(f2);
        //public File(File parent, String child)

        //给定父路径的File类型和子路径创建File对象
        File f3 = new File("C:\\Users\\jin\\Desktop");
        File f4 = new File(f3,"day10");
        System.out.println(f4);
    }
}

2. Common methods

After talking about the construction method of the File class, the following is the common method of the File class:

Common methods of the File class
Common method Description
getAbsolutePath() Get the absolute path of the file
getpath () Get creation path
getName() Get file or folder name
length() Get file byte length
import java.io.File;
public class Test02 {
    public static void main(String[] args) {
        //获取方法
        File f = new File("C:\\Users\\jin\\Desktop\\123.txt");

        //getAbsolutePath()
        //获取绝对路径(从盘符开始的路径就是绝对路径)
        System.out.println(f.getAbsolutePath());

        //getPath()
        //获取创建对象时的路径
        System.out.println(f.getPath());

        //getName()
        //获取文件名(获取最后一级名字)
        System.out.println(f.getName());

        //length()
        //获取文件大小,不能获取目录的大小
        //文件大小就是文件的字节数
        System.out.println(f.length());   //435字节
    }
}

3. Judgment method

         Judgment method, used to judge whether the file or folder exists, usually use the following

Judgment method
Judgment method Description
exists() Determine whether the path exists
isFile() Determine whether it is a file
isDirectory() Determine whether it is a folder (directory)

import java.io.File;
public class Test04 {
    //判断方法
    public static void main(String[] args) {
        File f = new File("day10\\src");
        //exists()
        //判断路径是否存在
        System.out.println(f.exists());

        //isFile()
        //判断是否是文件,如果不是文件或不存在false
        System.out.println(f.isFile());

        //isDirectory()
        //判断是否是文件夹(目录),如果不是文件夹或不存在false
        System.out.println(f.isDirectory());
    }
}

4. Create a delete method

        When the file or folder does not exist, you can directly use the File class to create it, as follows:

Create and delete methods
Create and delete methods Description
createNewFile() Create new file
delete() Delete ( 1. Folders with files cannot be deleted. 2. Files deleted by this method do not go through the recycle bin )
mkdir() Create a single-level folder
mkdirs Create multi-level folders
import java.io.File;
import java.io.IOException;
public class Test05 {
    //创建删除方法
    public static void main(String[] args) throws IOException {

        File f0 = new File("day10\\aaa\\sfsd.txt");
        File f = new File("day10\\aaa");

        //createNewFile()
        //创建一个文件
        f.createNewFile();

        //delete()
        //删除一个文件或空文件夹(不能删除有文件的文件夹)
        //删除方法不走回收站,你别删除有用的文件
        f0.delete();
        f.delete();

        //mkdir()
        //创建单层文件夹
        File f2 = new File("day10\\aaa");
        f2.mkdir();
        
        //mkdirs()
        //创建任意层文件夹
        File f3 = new File("day10\\bbb\\ccc");
        f3.mkdirs();
    }
}

5. Method of traversing directory

Directory traversal method
Traverse method Description
list() Get the names of all contents in the directory
listFiles() Get the File object form of all contents in the directory
import java.io.File;
public class Test06 {
    public static void main(String[] args) {
        File f = new File("C:\\Users\\jin\\Desktop\\day10");
        //list()
        //获取目录下所有内容的名称
        String[] list = f.list();
        //遍历
        for (String s : list) {
            System.out.println(s);
        }

        System.out.println("---------------------------");

        //listFiles()
        //获取目录下所有内容的File对象形式
        File[] files = f.listFiles();
        //遍历
        for (File file : files) {
            System.out.println(file);
        }
    }
}

IO style

       In the IO stream, I represents in, o represents out, and IO is the input and output of data.

       IO classification:

        1) According to the direction, it is divided into: input stream and output stream

        2) According to the type is divided into: byte stream and character stream

        And what I want to introduce is: byte input stream, byte output stream, character input stream and character output stream.

                                                  

1. Byte stream

Any data in the computer is stored in bytes, and byte streams can manipulate data in bytes

      1.1, byte output stream OutputStream

The byte output stream parent class OutputStream is an abstract method with the following commonly used methods. When we create an object, we usually use its subclass: FileOutputStream (introduced next)

Common methods of byte output stream parent class
method Description
close Release resources
write(byte[] b) Output byte array
write(byte[] b,int off,int len) Part of the output byte array, off means the start index, len means the number
write(int b ) Output one byte

      1.1.1, byte output stream subclass FileOutputStream

This class has four construction methods, as follows:

Features: 1) If the file to be written does not exist and no error will be reported, the corresponding file will be created

            2) If the first two construction methods below are used, there will be byte coverage problems, while the latter two will not

            3)构造方法只能指向文件,不能指向文件夹(报错:拒绝访问。)

构造方法
构造方法 说明
public FileOutputStream(File file) 向指定文件位置输出数据
public FileOutputStream(String name) 向指定字符串路径输出数据
public FileOutputStream(File file, boolean  b) 创建对象的同时是否续写,true表示续写
public FileOutputStream(String name,boolean  b) 创建对象的同时是否续写,true表示续写
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Test01 {
    public static void main(String[] args) throws FileNotFoundException {
        //字节输出流的构造方法
        /*
            注意事项:
                如果文件不存在构造方法会创建文件
                如果文件已存在构造方法会覆盖文件
                构造方法只能指向文件,不能指向文件夹(报错:拒绝访问。)
                true表示续写,如果文件存在不会覆盖之前的内容,在原来内容的基础上续写
         */
        //new FileOutputStream(String pathname) :参数表示路径名称
        //FileOutputStream fos = new FileOutputStream("day10\\123.txt");

        //new FileOutputStream(File file) :参数表示路径名称
        //FileOutputStream fos2 = new FileOutputStream(new File("day10\\123.txt"));

        //new FileOutputStream(String pathname,boolean b) 
       //:参数表示路径名称,第二个参数表示是否续写
        FileOutputStream fos = new FileOutputStream("day10\\123.txt",true);

        //new FileOutputStream(File file,boolean b) 
        //:参数表示路径名称,第二个参数表示是否续写
        //FileOutputStream fos2 = new FileOutputStream(new File("day10\\123.txt"),true);
    }
}

方法的使用演示:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test02 {
    //FileOutputStream的方法
    public static void main(String[] args) throws IOException {
        //创建对象
        FileOutputStream fos = new FileOutputStream("day10\\123.txt");

        //write(int b)  byte -128 ~ 127
        //输出一个字节,保存的是对应的字符
        fos.write(97);

        //write(byte[] b)
        //输出字节数组
        byte[] arr = {65,66,68,100,102};
        fos.write(arr);

        //write(byte[] b, int off, int len)
        //输出字节数组的一部分。off表示开始索引,len表示个数
        fos.write(arr,2,3);

        //close()
        //关闭流资源,关闭之后就不能用了
        fos.close();
    }
}

     1.2、输入流父类InputStream

常用方法
方法 说明
close() 关闭流资源
read() 每次读取一个字节,返回值代表的是字节
read(byte[] b) 每次读取一个数组的字节,返回值代表读取到的字节个数

     1.2.1.输入流子类FileInputStream

注意事项:
               1) 如果文件不存在,构造方法会报错 (报错:系统找不到指定的文件。)
                2)构造方法只能指向文件,不能指向文件夹(报错:拒绝访问。)

构造方法
方法 说明
FileInputStream(File file) 从指定的File文件读取数据
FileInputStream(String name) 从指定字符串路径位置读取数据

构造方法演示:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test04 {
    public static void main(String[] args) throws FileNotFoundException {
        //字节输入流FileInputStream的构造方法
        //FileInputStream(File file)
        //从指定的File文件读取数据
        FileInputStream fis = new FileInputStream(new File("day10\\123.txt"));

        //FileInputStream(String name)
        //从指定字符串路径位置读取数据
        //FileInputStream fis2 = new FileInputStream("day10\\123.txt");
    }
}

常用方法演示(读字节数组为例):

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
public class Test06 {
    public static void main(String[] args) throws IOException {
        //创建对象
        FileInputStream fis = new FileInputStream("day10\\123.txt");
        //read(byte[] b)
        //每次读取一个数组的字节,返回值代表读取到的字节个数
        //把数据放到数组中,返回的是字节个数
        //循环
        byte[] arr = new byte[5];
        int len;
        while((len=fis.read(arr)) != -1){
            System.out.print(new String(arr,0,len));
        }
        //close()
        //关闭流资源
        fis.close();
    }
}

2、字符流

字符流专门用来操作中文文本,因为一个中文占用多个字节

      2.1、字符输入流父类Reader

常用方法
方法 说明
close() 关闭流资源
read() 读取一个字符
read(char[] chs) 读取一个字符数组内容

     2.1.2、FileReader类

注意事项:
      1) 如果文件不存在,会抛出异常(报错:系统找不到指定的文件)
       2)构造方法只能写文件,不能写文件夹(报错:拒绝访问)

构造方法
方法 说明
FileReader(File file) 使用file对象路径创建输入流
FileReader(String fileName) 使用字符串路径创建输入流

使用方法:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Test04 {
    //FileReader的构造方法
    public static void main(String[] args) throws FileNotFoundException {
        FileReader fr = new FileReader("day10\\123.txt");
        //FileReader f2 = new FileReader(new File("day10\\123.txt"));
    }
}

一次读取一个字符数组:

import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Test06 {
    public static void main(String[] args) throws IOException {
        //创建对象
        FileReader fr = new FileReader("day10\\123.txt");

        //read(char[] arr)
        //每次读取多个字符,返回值表示读到的字符个数,如果读到了末尾返回-1
       //循环
        char[] chs = new char[5];
        int len;
        while((len=fr.read(chs)) != -1){
            System.out.println(new String(chs,0,len));
        }
        //关闭流资源
        fr.close();
    }
}

     2.2.字符输出流父类Writer

方法 说明
close() 关闭流资源
flush() 刷新
write(int c) 写出一个字符
write(char[] cbuf) 写出一个字符数组的内容
write(char[] b, int off, int len) 写出一个字符数组的一部分
write(String str) 写出一个字符串

     2.2.1、FileWriter类

注意事项:
        1) 如果文件不存在,会自动创建文件
        2) 如果文件已存在,会覆盖原有文件
        3) 构造方法中只能写文件,不能写文件夹(报错:拒绝访问。)
         4)如果加上一个true,表示在原有文件内容上续写

方法 说明
FileWriter(File file) 用File对象所表示的路径创建输出流对象
FileWriter(String fileName) File字符串所表示的路径创建输出流对象
FileWriter(File file,boolean b) 用File对象所表示的路径创建输出流对象,true表示续写
FileWriter(String fileName,boolean b) File字符串所表示的路径创建输出流对象,true表示续写

构造方法:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test01 {
    public static void main(String[] args) throws IOException {
        //字符输出流FileWriter构造方法

        //new FileWriter(String name)
        //FileWriter fw = new FileWriter("day10\\123.txt");

        //new FileWriter(File file)
        //FileWriter fw2 = new FileWriter(new File("day10\\123.txt"));

        //new FileWriter(String name,boolean b)
        //FileWriter fw = new FileWriter("day10\\123.txt",true);

        //new FileWriter(File file,boolean b)
        FileWriter fw = new FileWriter(new File("day10\\123.txt"),true);
    }
}

常用方法:

import java.io.FileWriter;
import java.io.IOException;
public class Ttest03 {
    public static void main(String[] args) throws IOException {

        //FileWriter的输出方法
        FileWriter fw = new FileWriter("day10\\123.txt");

        //write(int c)
        //写出一个字符
        fw.write(97);
        fw.write('a');
        fw.write('我');

        //write(char[] cbuf)
        //写出一个字符数组的内容
        char[] arr = {'a','b','c','d'};
        fw.write(arr);

        //write(char[] b, int off, int len)
        //写出一个字符数组的一部分
        fw.write(arr,2,2);

        //write(String str)
        //写出一个字符串
        fw.write("abcdefg");

        //关闭
        fw.close();
    }
}

字节流:
           操作文本文档以外的数据时一定使用字节流

字符流:
           操作文本文档就用字符流

Guess you like

Origin blog.csdn.net/weixin_43267344/article/details/108134283