io style 4

                                                 character stream

      We introduced the byte stream earlier. Let's take a look at the character stream today. The byte stream can read all files, but when there are Chinese characters in the file, how do we operate on these Chinese characters?

Let's first look at two ways to read files

public static void read() throws IOException{
        FileReader fr=new FileReader("e:\\java\\java.txt");
        int len=0;
        while((len=fr.read())!=-1){
            System.out.println (( char ) len);
        }
    }
    public static void read2() throws IOException{
        FileReader fr=new FileReader("e:\\java\\java.txt");
        int len=0;
        char[] ch=new char[1024];
        while((len=fr.read(ch))!=-1){
            System.out.println(new String(ch,0,len));
        }
    }

    In general, the second method is more efficient

Let's take a look at the method of writing something to a file with a character stream

public static void writer() throws IOException{
        FileWriter fw=new FileWriter("e:\\java\\java.txt",true);
        fw.write(100);
        fw.flush(); // Refresh, after calling the write method, you need to refresh to flush the characters to 
        fw.write("Hello" );
        fw.flush();
        char [] ch = {'i', 'l', 'o', 'v', 'e' };
        fw.write(ch);
        fw.close(); // with the function of refreshing once 
    }

Where flush is refresh, the operation is refreshed before each write, and then closed

                                                      buffered stream

  The byte stream and character stream mentioned above are relatively inefficient streams. Let's talk about a more efficient stream, a buffer stream. 

public static void read() throws IOException{
        FileInputStream fos=new FileInputStream("e:\\java\\demo.txt");
        BufferedInputStream bos=new BufferedInputStream(fos);
        int len=0;
        byte[]b=new byte[1024];
        while((len=bos.read(b))!=-1){
            System.out.println(new String(b,0,len));
        }
        bos.close();
    }

Here's how to read a file with a buffered stream

We can calculate the running time of the program, it is not difficult to see that this is the fastest method

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324787968&siteId=291194637