File operations and IO

long time no see ~

content

1. Documents

1.1 Ordinary file

1.1.1 Hard Disk

1.2 Directory file

1.2.1 Structure

1.2.2 Path

1.3 Classification of documents

2. Operation files in java

2.1 Related operations of the file system

2.2.1 Introduction of File class

2.2.2 List files

2.2.3 Create file

2.2.4 Create a directory

2.2.5 Delete files

2.2 Operations related to file content

2.2.1 Open file

2.2.2 Reading files

2.2.3 Write file

2.2.4 Close the file

3. Three cases of file manipulation

3.1 Find files and delete

3.2 Copying of ordinary files

3.3 Searching for file content


1. Documents

The files we often say are ordinary files stored on the hard disk. (This section mainly discusses common files)

1.1 Ordinary file

Files in the form of txt, jpg, mp3, etc. stored on the hard disk are called ordinary files.

1.1.1 Hard Disk

① Mechanical hard disk:

a. The basic structure of the mechanical hard disk: (below is a brief introduction to the mechanical hard disk)

Disk (platter): The medium that stores data

Heads and Motors: The Execution Section

Circuit Board: Control Section

b. Operating principle:

When the mechanical hard disk is powered on, the platters inside will run at high speed, and the magnetic head will find the corresponding data on the disk surface. However, due to the limited hardware structure of the mechanical hard disk, the higher the speed of the disk, the faster the read and write speed, and it is easy to know that the speed of the disk cannot be infinitely high, so it has been stagnant for 10 years. So we introduced the solid-state hard drive that we are going to talk about below

②Solid State Drive (SSD):

This is a solid state drive.

The hardware structure of solid-state drives is completely different from that of mechanical hard drives. The read and write speed of solid-state drives is much faster than that of mechanical hard drives.

 And we are now mainly talking about mechanical hard drives.

1.2 Directory file

1.2.1 Structure

In a computer, keeping and storing files is achieved through the "file system" in the operating system.

In the file system, the directories and files on the disk are generally organized through a tree structure, which is an N-forked number.

Let me give you an example:

This is what we call a tree structure

1.2.2 Path

①Absolute path:

An absolute path refers to a specific path that begins with a drive letter. For example: C:\Program Files\Java

②Relative path:

Starting with . or .., where . represents the current path

..represents the parent directory of the current path (superior path)

A relative path must have a reference directory. The relative path starts from the reference directory and finds the corresponding file according to the reference path.

For example: the benchmark path at this time is: C:\Program Files\Java. And at this point I'm looking for javac.exe.

./javac.exe is all that's needed for the above. . represents the current base path .

And to find src.zip you can write ../src.zip. .. is equivalent to returning to the upper-level path (C:\Program Files) of the benchmark, and then finding the target path.

 To explain in simple words, the absolute path is relative to the whole of the transaction, and the relative problem is relative to the part of the transaction.

1.3 Classification of documents

①Text file:

The file stores characters (essentially stored bytes, but adjacent bytes just form one character). Usually similar to .txt, .c, .java are text files.

②Binary file:

Files store bytes. Similar to .class,.jpg,.doc are binary files

③ How to distinguish between binary files and text files:

The easiest way is to open it with Notepad, if it is garbled, it is a binary file , otherwise it is a text file.

2. Operation files in java

2.1 Related operations of the file system

It refers to some functions that can be completed through the file resource manager. The File class is provided in Java, and a series of operations are completed through this class. We will focus on explaining it below.

2.2.1 Introduction of File class

①Construction method of File:

The construction method of File can pass in a path to specify a file. This path can be an absolute path or a relative path.

②Some methods of File:

③We demonstrate the operation for some of these methods:

Code:

import java.io.File;
import java.io.IOException;
public class demo1 {
    public static void main(String[] args) throws IOException {
        File f=new File("C:/ProgramData/test.txt");
        System.out.println("获取到文件的父目录:"+f.getParent());
        System.out.println("获取到文件名:"+f.getName());
        System.out.println("获取到文件路径:"+f.getPath());
        System.out.println("获取到文件的绝对路径:"+f.getAbsolutePath());
        //这里需要抛出一个异常,并且这里是化简过的绝对路径
        System.out.println("获取到文件的绝对路径:"+f.getCanonicalPath());
        System.out.println("===============");
        //这里的路径是一个基准路径
        File f1=new File("./ProgramData/test.txt");
        System.out.println("获取到文件的父目录:"+f1.getParent());
        System.out.println("获取到文件名:"+f1.getName());
        System.out.println("获取到文件路径:"+f1.getPath());
        System.out.println("获取到文件的绝对路径:"+f1.getAbsolutePath());
        //这里需要抛出一个异常,并且这里是化简过的绝对路径
        System.out.println("获取到文件的绝对路径:"+f1.getCanonicalPath());
    }
}

 To explain some of the content in the code:

2.2.2 List files

Code:

import java.io.File;
import java.util.Arrays;
public class demo2 {
    public static void main(String[] args) {
        File f = new File("./");
        //查看此目录下的内容(列出目录内容)
        System.out.println(Arrays.toString(f.list()));
        //按照file对象的方法打印
        System.out.println(Arrays.toString(f.listFiles()));
    }
}

result:

 

2.2.3 Create file

Code:

import java.io.File;
import java.io.IOException;
public class demo2 {
    public static void main(String[] args) throws IOException {
        //创建一个文件
        File f=new File("./test.txt");
        //判断文件是否存在
        System.out.println(f.exists());
        //创建文件
        f.createNewFile();
        //文件创建结束,判断是否存在
        System.out.println(f.exists());
    }
}

Output result:

2.2.4 Create a directory

①Create a directory:

Code:

import java.io.File;
import java.io.IOException;
public class demo2 {
    public static void main(String[] args) throws IOException {
        //创建一个文件
        File f=new File("./aa");
        //创建一个目录
        f.mkdir();
    }
}

result:

②Create multiple directories

Code:

import java.io.File;
import java.io.IOException;
public class demo2 {
    public static void main(String[] args) throws IOException {
        //创建一个文件
        File f=new File("./aa/bb/cc");
        //创建一个目录
        f.mkdirs();
    }
}

result:

 

2.2.5 Delete files

Code:

import java.io.File;
import java.io.IOException;
public class demo2 {
    public static void main(String[] args) throws IOException {
        //创建一个文件
        File f=new File("./test.txt");
        //判断文件是否存在
        System.out.println(f.exists());
        //删除文件
        f.delete();
        //删除文件后是否存在
        System.out.println(f.exists());
    }
}

Operation result:

2.2 Operations related to file content

For the reading and writing of file content, the Java standard library provides a set of classes, which are divided into two series according to the content of the file:

① Byte stream object, for binary files , read and write in bytes

Read: InputStream Write: OutputStream

②Character stream object, for text files , read and write in units of characters

Read: Reader Write: Writer

Notice! ! ! The above four categories are abstract classes, if we want to implement them, we need to use their subclasses

FileInputStream,FileOutputStream,FileReader,FileWriter。

This group is a special pointer to read and write to ordinary files

2.2.1 Open file

While instantiating the object, enter the specified path, which is not detailed here, but is reflected in the code

2.2.2 Reading files

InputStream and Reader both read files through the read method. Let's talk about the read method first:

a. No parameter version:

Read one byte at a time, the return value is the read byte (note! When -1 is read, it means the file has been read)
b. A parameter version:

Read several bytes at a time, put the read result into the specified array, and the return value is the number of bytes read
c. Three parameter version:

Read several bytes at a time, put the read result into the array specified in the parameter, and the return value is the number of bytes read. Notice! ! ! Here, the elements are not placed from the starting position of the array, but from the middle position (off subscript), and len indicates how many elements can be placed at most

②Read the file through inputStream

a. Read one byte at a time

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class demo2 {
    public static void main(String[] args) {
        InputStream inputStream = null;
        try {//创建对象,也是打开文件,有可能没有文件,因此需要抛异常
            inputStream = new FileInputStream("C:/Users/张洋洋的小布偶/Desktop/test.txt");//需要指定路径,可以是相对路径也可以是绝对路径,也可以是File对象
            //尝试一个一个字节的读,把整个文件读完
            while(true){
                int x = inputStream.read();
                if(x == -1){
                    break;//表示读完了所有的字节
                }
                System.out.println(x);//打印
            }
        } catch (IOException e) {
            //这个包含了FileNotFoundException(子类),因此可以合并,IO操作失败的可能性是非常大的
            e.printStackTrace();
        }finally {
            //读完之后需要关闭文件,释放资源
            try {
                inputStream.close();//这个放在finally里面更好有需要把定义放到外面去
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

(We can find that it is quite troublesome to use finally to close the file, but at the same time, java provides a method try, which can be automatically closed after reading the try, we will demonstrate it below)

b. Read multiple bytes at a time

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class demo2 {
    public static void main(String[] args) {
        try (InputStream inputStream = new FileInputStream("C:\\Users\\张洋洋的小布偶\\Desktop/test.txt")) {
            while (true) {
                byte[] tmp = new byte[1024];
                int x = inputStream.read(tmp);
                if (x == -1) {
                    break;//表示读完了所有的字节
                }
                for (int i = 0; i < x; i++) {
                    //打印
                    System.out.println(tmp[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 The result is as follows:

③ Read the file through Reader

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class demo2 {
    public static void main(String[] args) {
        try(Reader reader = new FileReader("C:\\Users\\张洋洋的小布偶\\Desktop/test.txt")) {
            while (true){
                char[] c = new char[1024];
                int x = reader.read(c);//一次读多个
                if(x == -1){
                    break;
                }
                /*for (int i = 0; i < x; i++) {
                    System.out.println(c[i]);
                }*/
                String s = new String(c,0,x);//如果传入的是byte也可以指定字符编码
                System.out.println(s);//这样也可以读
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result is as follows:

2.2.3 Write file

①OutputStream

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class demo2 {
    public static void main(String[] args) {
        try (OutputStream outputStream = new FileOutputStream("C:\\Users\\张洋洋的小布偶\\Desktop/test.txt")) {
            /*outputStream.write(98);
            outputStream.write(97);一次写一个
            outputStream.write(97);*/
            //也可以一次写多个
            byte[] b = new byte[]{98,97,97};
            outputStream.write(b);//一次写多个     这里的写操作每次按照写方式打开文件,都会清空原有的文件的内容,然后再从起始位置往后写
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result is as follows:

 ②Writer

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class demo2 {
    public static void main(String[] args) {
        try(Writer writer = new FileWriter("C:\\Users\\张洋洋的小布偶\\Desktop/test.txt")){
            writer.write("aaa");//写操作
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result is as follows:

 

2.2.4 Close the file

After each read, you need to close the file to release resources

3. Three cases of file manipulation

3.1 Find files and delete

① Thought: recursion

②Code:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
//实现查找文件并删除文件
public class Demo13 {
    public static void main(String[] args) {
        //先输入要扫描的目录,以及要删除的文件名
        Scanner input = new Scanner(System.in);
        System.out.println("请输入要扫描的路径:");
        String rootDirPath = input.next();
        System.out.println("请输入要删除的文件名:");
        String toDeleteName = input.next();
        File rootDir = new File(rootDirPath);//构建文件对象
        if(!rootDir.isDirectory()){
            //不是一个目录
            System.out.println("你输入的路径有误");
            return;//可以抛一个异常
        }
        //遍历这个目录,寻找要删除的文件
        scanDir(rootDir,toDeleteName);
    }
    public static void scanDir(File rootDir,String toDeleteName){
        File[] files = rootDir.listFiles();
        if(files == null){
            //rootDir是空目录,返回
            return;
        }
        //不是空目录就遍历此目录里面的所有内容,如果是普通文件就看是不是要删除的文件,不是文件是目录的话,就再遍历这个目录
        for(File f : files){//列出rootDir里面有什么内容
            if(!f.isFile()){
                scanDir(f,toDeleteName);
            }
            if(f.isFile()){
                if(f.getName().contains(toDeleteName)){
                    //不要求名字完全一样,只要文件名中包含了关键字就可以删除
                    //进行删除操作
                    deleteFile(f);
                }
            }
        }
    }
    public static void deleteFile(File f){
        try {
            System.out.println(f.getCanonicalPath() + "确认要删除文件吗(Y/N)");
            Scanner input = new Scanner(System.in);
            String chose = input.next();
            if(chose.equals("Y") || chose.equals("y")){
                f.delete();//进行删除
                System.out.println("文件删除成功");
            }else{
                System.out.println("文件放弃删除");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.2 Copying of ordinary files

①Find the file and copy it

②Code:

import java.io.*;
import java.util.Scanner;
//文件复制,需要让用户支出两个文件路径,一个是原路径(被复制的文件),另一个是目标路径(复制后生成的文件)
public class Demo14 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入要拷贝的源路径:");
        String str = input.next();
        System.out.println("请输入要拷贝的目标路径:");
        String sub = input.next();
        File file = new File(str);
        if(!file.isFile()){//需要判断是不是正确的路径,目标路径不需要判断,因为没有的话,是会自己创建的
            System.out.println("不是一个正确的源路径");
            return;
        }
        //将源文件里面的内容读出来,然后再用写操作写到目标文件中去
        try(InputStream inputStream = new FileInputStream(str)) {
            try(OutputStream outputStream = new FileOutputStream(sub)) {
                byte[] b = new byte[1024];
                while(true){
                    int x = inputStream.read(b);
                    if(x == -1){
                        break;
                    }
                    outputStream.write(b,0,x);//需要指定长度,不能把所有的b都放进去
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.3 Searching for file content

① Thought: recursion

②Code:

import java.io.*;
import java.util.Scanner;
//进行文件内容的查找,扫描指定目录,找到名称或内容中包含指定字符的所有普通文件(不包含目录)
public class Demo15 {
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入要扫描的文件路径:");
        String rootDirPath = input.next();
        System.out.println("请输入要查询的关键字:");
        String word = input.next();
        File rootDir = new File(rootDirPath);
        if(!rootDir.isDirectory()){
            System.out.println("输入的路径非法!");
            return;
        }
        sDir(rootDir,word);
    }
 
    private static void sDir(File rootDir, String word) throws IOException {
        File[] files = rootDir.listFiles();
        if(files == null){
            return;
        }
        for (File f:files) {
            if(f.isDirectory()){
                sDir(f,word);
            }
            if(f.isFile()){
                //针对文件进行查找
                if(containsWord(f,word)){
                    System.out.println(f.getCanonicalPath());
                }
            }
        }
    }
 
    private static boolean containsWord(File f, String word) {
        StringBuilder stringBuilder = new StringBuilder();
        //把f中的内容都读出来,放到StringBuilder中,看是否包含关键字
        try(Reader reader = new FileReader(f)){
            char[] c = new char[1024];
            while(true){
                int x = reader.read(c);
                if(x == -1){
                    break;
                }
                stringBuilder.append(c,0,x);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //indexOf返回的是子串的下标,如果word存在,那么下标一定不是-1,
        return stringBuilder.indexOf(word) != -1;
    }
}

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/124292333