Introduction and usage of File class and InputStream, OutputStream

1. File class

1.1 Introduction to the File class

The File class belongs to the java.io.File package. An object of the File class represents a file or a file directory (commonly known as a folder)

1.2 Create an instance of the File class

Before introducing the instance creation of the File class, you need to talk about relative paths and absolute paths

Relative path: Compared with the path specified under a certain path, it is a relative path

Absolute path: The absolute path is the path of the file or file directory including the drive letter (d:\)

When our File class is created, there are three commonly used construction methods:

The first is to directly enter the corresponding string to indicate the location of the file

@Test
    public void test1(){
        //构造器一
       File file1=new File("hello.txt"); //相对于当前module
       File file2=new File("D:\\Git\\java\\JavaSenior\\day_05\\he.txt"); //绝对路径
       System.out.println(file1);
       System.out.println(file2);
    }

The second is to use a string to represent the file directory

 //构造器二
        File file3=new File("D:\\Git\\java","JavaSenior");//文件目录
        System.out.println(file3);

The third is a file in a file directory

//构造器三
        File file4=new File(file3,"hi.txt"); //相当于在JavaSenior下面的一个文件
        System.out.println(file4);

1.3 Common methods of the File class

 /*
    适用于文件目录:
    public String[] list():获取指定目录下的所有文件或者文件目录的名称数组
    public File[] listFiles():获取指定目录下的所有文件或者文件目录的File数组
      */
    @Test
    public void test2(){
        File file1=new File("hello.txt");
        File file2=new File("D:\\io\\hi.txt");
        System.out.println(file1.getAbsolutePath());//获取绝对路径
        System.out.println(file1.getPath());  //获取路径
        System.out.println(file1.getName()); //获取名字
        System.out.println(file1.getParent()); //获取上层文件目录,若无,返回null
        System.out.println(file1.length()); //获取文件长度(字节数),不能获取目录的长度
        System.out.println(file1.lastModified()); //获取最后一次的修改时间,返回值为毫秒数
}

public boolean isDirectory():判断是否是文件目录
public boolean isFile():判断是否是文件
public boolean exists():判断是否存在
public boolean canRead():判断是否可读
public boolean canWrite():判断是否可写
public boolean isHidden():判断是否隐藏


 
    创建硬盘中对应的文件或文件目录:
    public boolean creatNewFile():创建文件。若文件存在,则不创建,返回false
    public boolean mkdir():创建文件目录.如果目录存在,则不创建
    public boolean mkdirs():创建文件目录,如果上层文件目录不存在,一并创建
    删除磁盘中的文件或文件目录
    public boolean delete():删除文件或文件夹
    注:Java中的删除不走回收站
  

2 Use of InputStream and OutStream

2.1 Introduction of InputStream and OutStream

First of all, in java, according to the different data units , it can be divided into byte stream and character stream. If according to the different flow direction, it can be divided into input stream and output stream. Among them, InputStream belongs to byte input stream, and OutStream belongs to byte output stream

2.2 Use of InputStream and OutStream

First of all, InputStream is an abstract base class . We often use the implementation class FileInpustream of InputStream to instantiate. We also often use FileOutputStream to instantiate OutStream. The basic usage steps can be divided into

(The following takes InputStream as an example)

1. Make files

  File file = new File("hello.txt");

2. Create flow

 FileInputStream fs=new FileInputStream(file);

3. Read data

 byte[] buffer = new byte[5];
            int len; //记录每次读取的字节个数
            while ((len = fs.read(buffer)) != -1)
            {
                String str=new String(buffer,0,len);
                System.out.print(str);
            }

Note: The read operation will read one byte in the file at a time, but will return -1 when it is empty

4. Close resources

 if(fs!=null) {
                    fs.close();
}

In order to ensure that stream resources must be closed, we often use the try-catch-finally statement to perform stream operations

At the same time, remember to handle exceptions that occur during file operations. The overall code is as follows:

 public void test() {
        FileInputStream fs=null;
        try {
            //1.造文件
            File file = new File("hello.txt");
            //2.造流
            fs = new FileInputStream(file);
            //3.读数据
            byte[] buffer = new byte[5];
            int len; //记录每次读取的字节个数
            while ((len = fs.read(buffer)) != -1)
            {
                String str=new String(buffer,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            try {
                if(fs!=null) {
                    fs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/yss233333/article/details/127290724