Java is really not difficult (19) File class, IO stream

IO style:

IO stream overview:

IO : Input/Output
stream : It is an abstract concept and a general term for data transmission. That is to say, the transmission of data between devices is called a stream. The essence of the stream is that the data transmission IO stream is used to deal with the problem of data transmission between devices. Common applications: file copy; file upload; file download, etc. In a word, it involves To transmission, all involve streams.

IO flow system diagram:
insert image description here
insert image description here

Since IO is an operation involving files, it must be inseparable from the technology of file operation:

File class:

The File class is the only object in the java.io package that represents the disk file itself. The File class defines some methods to manipulate files, mainly to obtain or process information related to disk files, such as file names, file paths, access rights and modification dates, etc., and to browse subdirectory hierarchies.
The File class represents information related to working with files and the file system. The File class does not have the ability to read information from and write information to the file, it only describes the properties of the file itself. So it is combined with IO for read and write operations.

Let's first look at a summary of the methods commonly used in the File class:
insert image description here
use createNewFile() to create a file:

public class test01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
		
		//先建立一个File对象,并传入路径
        File file1 = new File("G://abc.txt");
        //创建空文件,如果没有存在则新建一个,并且返回True,如果存在了就返回false
        System.out.println(file1.createNewFile());   
}        

If there is no such file in the directory after execution, it will create one and return true, if it already exists, it will return false, which means the creation failed.
insert image description here
Create a directory with mkdir():

File file2 = new File("G://a");
	System.out.println(file2.mkdir());   
//创建一个目录,如果没有存在则新建一个,并且返回True,如果存在了就返回false

Use mkdirs() to create multilevel directories:

File file3 = new File("G://a//b//c");
        System.out.println(file3.mkdirs());   
//创建多级目录,如果没有存在则新建一个,并且返回True,如果存在了就返回false

insert image description here

Then we need to use the functions in the IO stream to input and output files:
first introduce four commonly used streams:

  • Byte input stream: InputStream
  • Byte output stream: OutputStream
  • Character input stream: Reader
  • Character output stream: Writer

Why are there two streams of bytes and characters?

In ASCII code , one English letter (case-insensitive) is one byte, and one Chinese character is two bytes.
In UTF-8 encoding , one English word is one byte, and one Chinese word is three bytes.
In Unicode encoding , one English is one byte, and one Chinese is two bytes.

So we know that the computer reads the data one by one. When the file contains numbers or English, it can be read normally because it occupies one byte.
So what if it's Chinese characters? It also occupies at least two bytes. If a Chinese character is split and read, there must be a problem with the display.

Summary:
If the data is opened through the Notepad software that comes with Window, we can still read the content inside, use the character stream, otherwise use the byte stream. If you don't know which type of stream to use, use a byte stream!

The following is a summary table of method names for the four stream-corresponding functions:
insert image description here

Byte output stream:

We use the byte output stream to write a sentence to the abc.txt file:

public class test01 {
    
    
    public static void main(String[] args) {
    
    

        try{
    
    
              //创建输出流对象:
            OutputStream fos = null;
            fos = new FileOutputStream("G://abc.txt");
            String str = "今天的博客是IO流";
            //先将需要写入的字符打散成数组:
            byte[] words = str.getBytes();
            //使用写入的功能
            fos.write(words);

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

After running:
insert image description here

Byte input stream (read from file to console):

We know that if there are Chinese characters in the file and the byte input stream is used, then the display must be garbled. If there are four words "I love China" in the file now, use the following code:

public class test02 {
    
    
    public static void main(String[] args) {
    
    
        //创建字节输入流对象:
        InputStream fis = null;
        try{
    
    

            fis = new FileInputStream("G://abc.txt");
            int data;
            //fis.read()取到每一个字节通过Ascll码表转换成0-255之间的整数,没有值返回-1
            while((data=fis.read())!=-1){
    
    
                //(char) data 将读到的字节转成对应的字符
                //中文的字符是2+个字节组成
                System.out.print((char) data);
            }

        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            try{
    
    
                fis.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

The output result is:
insert image description here
Then replace the information in the file with English and numbers:
insert image description here
Conclusion: The file reading with Chinese characters cannot use byte stream

Character output stream:

We use the character output stream to write a few sentences to the abc.txt file:

public class test03 {
    
    
    public static void main(String[] args) {
    
    

        try{
    
    
            //使用字符输出流的FileWriter写入数据
            Writer fw = new FileWriter("G://abc.txt");
            fw.write("我们在学Java");
            fw.write("一起加油");
            fw.close(); //关闭资源
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

insert image description here
No problem, we found that it is more convenient to use the character stream to write Chinese characters.

Character input stream:

You can set up a cache stream to improve the efficiency of getting values:

public class test04 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //创建字符输入流对象:
        Reader fr = null;
        try{
    
    
          
            fr = new FileReader("G:/abc.txt");
           
            //借助字符流对象创建了字符缓存区 把字符一个一个的取到后先放到缓存区
            //然后一起再读写到程序内存来,效率更高
            BufferedReader br = new BufferedReader(fr);

            //先去缓存区一行一行的读取
            String line = br.readLine();

            while(line != null){
    
    
                System.out.println(line);
                line = br.readLine();
            }
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                fr.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }

When the information in the file is multiple lines:
insert image description here

Byte stream and character stream summary:

  • IO is the input and output of files. We need to use streams if we want to write to files, or send messages to other users through programs.
  • The IO stream is divided into byte stream and character stream. The byte stream is IO in bytes, and the character stream is IO in characters. Usually, byte streams are used to read and write pictures, video and audio. Chinese character stream is recommended.

Finally , there are many ways to operate the IO stream, such as copying files, buffering streams (adding buffering functions to avoid frequent reading and writing of hard disks), converting streams (realizing the conversion between byte streams and character streams), and data streams (providing the basis for converting The data type is written to the file, or read out) and so on, you can read the articles of other bloggers, continue to cheer!

insert image description here

Guess you like

Origin blog.csdn.net/m0_57310550/article/details/123261674