File operation [Java]

CSDN Topic Challenge Phase 2
Participating Topic: Java Technology Sharing

document

The concept of files

A file is an abstracted independent unit stored on the hard disk and used to save data;

file path

The path of the file generally has:

  • Absolute path: starting from the root directory of the file and reaching the path of the file itself; usually with a drive letter;
  • Relative path: Starting from any directory, the path to the current file itself;

Through the path of the file, we can quickly locate the location of the file in the system;

Classification of documents

Generally, according to the different data saved in the file, we divide the file into:

  • Binary files: files that have not been encoded by character sets, the rules are complex;
  • Text file: a file encoded by a character set with simple rules;

Both text files and binary files are stored binary 0 and 1, but there are differences due to different encoding situations;

File system

Files are also managed by the operating system. The module used to manage files in the operating system kernel is called a file system;
java also provides a series of packages for files, which helps us more conveniently manage files. Operation, namely the File class;

The construction method of File

import java.io.File;

public class demo1 {
    
    
    public static void main(String[] args) {
    
    
        
        //File(String pathname) 根据文件路径创建一个新的 File 实例;
        File file1=new File("d:/test.txt");
        //File(File parent, String child) 根据父目录 + 孩子文件路径,创建一个新的 File 实例
        File file2=new File("d:/tmp","./tmp/test");
    }
}

To use the File class, you need to import the package: java.io.File;
The path of the File class construction method when creating an instance can be an absolute path or a relative path; the
construction method is to create an instance of a File object, and a File object does not represent a file really exist;

Basic methods of the File class

  • Access the basic properties of a file:
public static void main(String[] args) {
    
    

        //File(String pathname) 根据文件路径创建一个新的 File 实例;
        File file1=new File("./test.txt");
        //返回对象的父目录文件路径
        System.out.println(file1.getParent());
        //返回对象的文件名称
        System.out.println(file1.getName());
        //返回对象的文件路径
        System.out.println(file1.getPath());
        //判断对象描述的文件是否存在
        System.out.println(file1.exists());
        //返回对象的绝对路径
        System.out.println(file1.getAbsolutePath());
        
    }

insert image description here

  • Creation of documents;
import java.io.File;
import java.io.IOException;


public class demo1 {
    
    
    public static void main(String[] args) throws IOException {
    
    

        //File(String pathname) 根据文件路径创建一个新的 File 实例;
        File file1=new File("./test.txt");

        //判断对象描述的文件是否存在
        System.out.println(file1.exists());
        //判断对象描述的文件是否是一个普通文件
        System.out.println(file1.isFile());
        //根据对象自动创建一个空白文件,创建成功返回true;
        System.out.println(file1.createNewFile());
        System.out.println(file1.exists());
        System.out.println(file1.isFile());
        System.out.println(file1.getAbsolutePath());


    }
}

insert image description here
At this point, a file is actually created successfully:
insert image description here

  • deletion of files;
import java.io.File;
import java.io.IOException;

public class demo1 {
    
    
    public static void main(String[] args) throws IOException {
    
    

        File file1=new File("./test2.txt");
        System.out.println(file1.exists());
        System.out.println(file1.createNewFile());
        System.out.println(file1.exists());
        System.out.println(file1.delete());
        System.out.println(file1.exists());
    }
}

insert image description here

delete() According to the File object, delete the file. Return true after successful deletion;

public static void main(String[] args) throws IOException {
    
    

        File file1=new File("./test2.txt");
        System.out.println(file1.exists());
        System.out.println(file1.createNewFile());
        System.out.println(file1.exists());
        //程序退出时删除
        file1.deleteOnExit();
        System.out.println(file1.exists());
    }

insert image description here

  • creation of directories;
import java.io.File;
import java.io.IOException;

public class demo1 {
    
    
    public static void main(String[] args) throws IOException {
    
    

        File file1=new File("tmp/test.txt/123");
        System.out.println(file1.exists());
        System.out.println(file1.isDirectory());
        //创建目录
        System.out.println(file1.mkdir());
        //创建目录,同时创建中间目录
        System.out.println(file1.mkdirs());
        System.out.println(file1.exists());

    }
}

insert image description here

When using mkdir() to create a directory, if the intermediate directory does not exist, it cannot be created successfully; using mkdirs() can create an intermediate directory at the same time;

file read and write

The reading and writing of file content is actually a process of data flow; the so-called data flow refers to the process of sending data records continuously rather than in batches; Java provides a special class for reading and writing files, namely
InputStream and OutputStream, and Reader and Writer;

InputStream

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class demo1 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File file=new File("./test.txt");
        file.createNewFile();
        System.out.println(file.getAbsolutePath());
        InputStream inputStream=null;
        //打开文件
        inputStream=new FileInputStream("test.txt");
        //读取文件
        while (true){
    
    
            int a=inputStream.read();
            if (a==-1){
    
    
                break;
            }
            System.out.println(a);
        }

        //关闭文件
        inputStream.close();
    }
}

When executing the above code, you must first make the file exist, and at the same time write certain content in the file, for example:
insert image description hererunning result:
insert image description herethe above running result is the decimal representation of the ASCII code of hello;

Since InputStream cannot be instantiated directly (modified by abstract), it is done with the help of subclass FileInputStream;

We use read() to read the contents of the file, and the read() method also provides various forms to read:

insert image description here

The first form is to read one byte at a time, usually by means of loop reading, and the above code adopts this form;

//读取文件
        byte [] b=new byte[1024];
        int len=inputStream.read(b);
        System.out.println(len);
        for (int i=0;i<len;i++){
    
    
            System.out.println(b[i]);
        }

insert image description here

The second form is done with the help of an array;

public static void main(String[] args) throws IOException {
    
    
        File file=new File("./test.txt");
        file.createNewFile();
        System.out.println(file.getAbsolutePath());
        InputStream inputStream=null;
        //打开文件
        inputStream=new FileInputStream("test.txt");
        //读取文件
        byte [] b=new byte[1024];
        int len=inputStream.read(b);
        String s=new String(b,0,len);
        System.out.println(s);
        //关闭文件
        inputStream.close();
    }

insert image description here

The third form is: for the content in the array, start reading from the position of the off subscript, and read the length of len;
when the content in the file is in Chinese, in order to avoid garbled characters, you can continue to specify characters after the third parameter The encoding method, that is, String s = new String(b, 0, len, “UTF-8”);

The role of inputStream is actually relative to the role of a "remote control", because the file is stored on the hard disk, and it is undoubtedly difficult to directly operate the hard disk, so we construct an object associated with the file in the memory, namely inputStream, by operating this object to achieve the purpose of operating files; in the computer, the object that acts as a "remote control" function is called a "handle";

After reading the file, it is very important to close the file; in simple terms, closing the file in time can release resources. In addition, due to the existence of the file description table, the file description table is an attribute in the PCB. It is a sequential table structure. Each element represents a file opened by the current process, and the subscript of each element It is called a "file descriptor", so each opened file occupies a position in the file description table. Since the file description table has a certain capacity limit, if you just blindly open the file without timely If you close it, you will naturally be unable to open other files in the end; in addition, if you forget to close the file after opening it, it will also cause the leakage of file resources. Since this leakage is a gradual process, you may not be able to detect this leakage in time. Brings greater security risks; therefore, be sure to close the file in time after opening the file;

For the integrity and security of our above code, we can make the following improvements:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


public class demo1 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File file=new File("./test.txt");
        file.createNewFile();
        
        InputStream inputStream=null;
        try{
    
    
            //打开文件
            inputStream=new FileInputStream("test.txt");
            //读取文件
            byte [] b=new byte[1024];
            int len=inputStream.read(b);
            String s=new String(b,0,len);
            System.out.println(s);
        }catch(IOException e){
    
    
            e.printStackTrace();
        }finally {
    
    
            try{
    
    
                //关闭文件
                inputStream.close();
            }catch (IOException e){
    
    
                e.printStackTrace();
            }
        }
        
       
    }
}

Add a try-catch operation to the core code, and throw an exception when the file is not closed in time;
in addition, there is a more convenient and safe method:

public class demo1 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File file=new File("./test.txt");
        file.createNewFile();


        try(InputStream inputStream=new FileInputStream("test.txt")){
    
    
            //打开文件

            //读取文件
            byte [] b=new byte[1024];
            int len=inputStream.read(b);
            String s=new String(b,0,len);
            System.out.println(s);
        }catch(IOException e){
    
    
            e.printStackTrace();
        }


    }
}

This way of writing will automatically call the close method of inputStream after the execution of try is completed; this is an operation of try with resources, which can be performed for classes that implement the Closeable interface;

The above reading using InputStream is actually a way of byte stream, we can also use the way of character stream to read:

Reader

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


public class demo2 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        Reader reader=new FileReader("test.txt");
        char [] buffer=new char[1024];
        int len=reader.read(buffer);
        for (int i=0;i<len;i++){
    
    
            System.out.println(buffer[i]);
        }
        reader.close();
    }
}

As the name implies, a character stream is a stream in units of characters, which is generally used to manipulate text files;

Scanner

In the above example, using InputStream to read is a bit cumbersome, so we try to use the Scanner class to solve it:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class demo3 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        InputStream inputStream=new FileInputStream("test.txt");
        Scanner scanner=new Scanner(inputStream);
        String s=scanner.next();
        System.out.println(s);
        inputStream.close();
    }
}

insert image description here

OutputStream

Use the writer() method of OutputStream to write characters, and writer() also provides a variety of forms:
insert image description here

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;


public class demo4 {
    
    
    public static void main(String[] args) {
    
    
        try(OutputStream outputStream=new FileOutputStream("test.txt")) {
    
    
            //write (int b)
            outputStream.write('h');
            outputStream.write('e');
            outputStream.write('l');
            outputStream.write('l');
            outputStream.write('o');


            String s="happy everyday";
            outputStream.write(s.getBytes());
            //write(byte[] b)
            byte[] str=new byte[]{
    
    'g','o','o','d'};
            outputStream.write(str);
            //write(byte[] b,int off,int len)
            int len=str.length;
            outputStream.write(str,0,len);

        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

Writer

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

public class demo5 {
    
    
    public static void main(String[] args) {
    
    
        try (Writer writer = new FileWriter("test.txt")) {
    
    
            writer.write("hello world");
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

The way Writer writes characters is also the way of character stream;

PrintWriter

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;


public class demo6 {
    
    
    public static void main(String[] args) {
    
    
        try(OutputStream outputStream=new FileOutputStream("test.txt")){
    
    
            PrintWriter printWriter=new PrintWriter(outputStream);
            printWriter.println("hhhhhhhhhhh");
        }catch (IOException e){
    
    
            e.printStackTrace();
        }
    }
}

The PrintWriter class can also complete the output, and the PrintWriter class also provides methods for outputting different forms of results, namely print/println/printf;

over!

Guess you like

Origin blog.csdn.net/weixin_54175406/article/details/127152629