Home  >  Article  >  Java  >  Introduction and example analysis of File class and IO stream in Java

Introduction and example analysis of File class and IO stream in Java

王林
王林forward
2023-04-20 20:28:09945browse

    IO stream:

    IO stream overview:

    IO : Input/Output (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 a stream is data transmission. IO streams are used to deal with data transmission problems between devices. Common applications: file copying; file uploading; file downloading, etc. In short, it involves Everything about transmission involves streams.

    IO flow system diagram:

    Introduction and example analysis of File class and IO stream in Java

    Introduction and example analysis of File class and IO stream in Java

    ##Since IO is an operation involving files, then 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 operate files, mainly used to obtain or process information related to disk files, such as file name, file path, access permissions, modification date, etc., and can also browse the subdirectory hierarchy.

    The File class represents information related to processing files and file systems. The File class does not have the function of reading information from files and writing information to files. It only describes the properties of the file itself. So it is paired with IO for reading and writing operations.

    Let’s first look at a summary diagram of the commonly used methods of the File class:

    Introduction and example analysis of File class and IO stream in Java

    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 the file does not exist in the directory after execution, it will create one and return true. If it already exists, it will return false, indicating that the creation failed.

    Introduction and example analysis of File class and IO stream in Java

    Use mkdir() to create a directory:

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

    Use mkdirs() to create a multi-level directory :

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

    Introduction and example analysis of File class and IO stream in Java

    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, byte and character?

    In ASCII code, one English letter (regardless of upper and lower case) 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 word is one byte, and one Chinese word is two bytes.

    So we know that the computer reads 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 occupies at least two bytes. If a Chinese character is split and read, there will definitely be a problem with the display.

    Summary: If the data is opened through the Notepad software that comes with Windows, and 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 corresponding to the four streams:

    Introduction and example analysis of File class and IO stream in Java

    Byte output stream:

    We use the byte output stream to write a sentence in 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:

    Introduction and example analysis of File class and IO stream in Java

    Byte input stream (read from file to console):

    We know that if the file contains Chinese characters and uses the byte input stream, the display will definitely be garbled. If the file now contains For the four words "I love China", 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:

    Introduction and example analysis of File class and IO stream in Java

    ##Then change the information in the file into English and numbers:

    Introduction and example analysis of File class and IO stream in Java

    Conclusion: Files with Chinese characters cannot be read using byte streams

    字符输出流:

    我们使用字符输出流给abc.txt文件里面写几句话:

    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();
            }
        }
    }

    Introduction and example analysis of File class and IO stream in Java

    也没用问题,我们发现,使用字符流写中文汉字更方便。

    字符输入流:

    可以设置缓存流提高获取值的效率:

    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();
                }
            }
        }

    当文件内的信息为多行的时候:

    Introduction and example analysis of File class and IO stream in Java

    字节流和字符流总结:

    • IO是文件的输入和输出,我们要想去对文件或者写,或者通过程序发送消息给另外的用户都要用到流。

    • IO流分 字节流和字符流,字节流是以字节为单位IO,字符流是以字符为单位IO;通常读写图片、视频音频等用字节 流,如果读写文件的内容比如中文建议用字符流。

    The above is the detailed content of Introduction and example analysis of File class and IO stream in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete