Output stream of IO Stream in Java | Lebyte

Posted by infyportalgroup on Thu, 01 Aug 2019 10:15:35 +0200

Hello everyone, Lebyte Xiaole is here again. What I brought to you in the last article is: the input stream of IO stream in Java | Lebyte. This article will continue to talk about the output stream of IO stream.

I. Output stream

1. Abstract classes: OutputStream and Writer

Output Stream and Writer are very similar.
The following methods are included in OutputStream:

In Writer, because the character stream is directly operated on by characters, Writer can use strings instead of character arrays, that is, String objects as parameters. Contains the following methods:

2. File Node Classes: FileOutputStream and FileWriter

FileOutputStream and FileWriter, both node flows, are directly associated with the specified file.

public class WriteFile {
    public static void main(String[] args) {
        //1. Establish a connection to File object source destination
        File dest=new File("c:/IO/print.txt");
        //2. Select Output Stream File Output Stream
        OutputStream out=null;
        //Writing out a file in the form of additions must be true or it will be overwritten
        try {
            out=new FileOutputStream(dest,true);
            //3. Operation
            String str="shsxt is very good \r\n good good good";
            //Converting strings to byte arrays
            byte[] data=str.getBytes();
            out.write(data,0,data.length);
            out.flush();//Forced refresh
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("file cannot be found");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("File Writing Failure");
        }finally{
            try {
                if(out!=null){
                out.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("Close Output Loss Failure");
            }
        }
    }
}
//1. Creating Sources
        File dest=new File("f:/IO/char.txt");
//2. Selective flow
        Writer    wr=new FileWriter(dest,true);
//3. Write
    String str="Hoe standing grain gradually pawning a midday\r\n It's hard for yard farmers.\r\n A small broken book\r\n Read all morning";
           wr.write(str);
        //Additional content
        wr.append("I just added it in.");
        wr.flush();//Forced brush out
//4. Closing resources
        wr.close();

Combining input and output streams, file copy can be realized.

public static void copyFile(String srcPath, String destPath) throws FileNotFoundException,IOException{
        // 1. Establish a contact source (existing and file) destination (file may not exist)
        File src = new File(srcPath);
        File dest = new File(destPath);
        if(!src.isFile()){//Throw an exception when it's not a file or null
            System.out.println("Only files can be copied");
            throw new IOException("Only files can be copied");
        }
        // 2. Selective flow
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dest);
        // 3. Operation
        byte[] flush = new byte[1024];
        int len = 0;
        // read
        while (-1 != (len = in.read(flush))) {
            // Write out
            out.write(flush, 0, len);
        }
        out.flush();// Forced brush out
        // Close the flow first open and then close
        out.close();
        in.close();
    }

3. Buffered Output Stream and Buffered Writer

Buffered Writer has a new method, newLine(), which can not produce polymorphism.

public static void copyFile(String srcPath, String destPath) throws FileNotFoundException,IOException{
        // 1. Establish a contact source (existing and file) destination (file may not exist)
        File src = new File(srcPath);
        File dest = new File(destPath);
        if(!src.isFile()){//Throw an exception when it's not a file or null
            System.out.println("Only files can be copied");
            throw new IOException("Only files can be copied");
        }
        // 2. Selective flow
        InputStream in = new BufferedInputStream(new FileInputStream(src));
        OutputStream out =new BufferedOutputStream(new FileOutputStream(dest));
        // 3. Operation
        byte[] flush = new byte[1024];
        int len = 0;
        // read
        while (-1 != (len = in.read(flush))) {
            // Write out
            out.write(flush, 0, len);
        }
        out.flush();// Forced brush out
        // Close the flow first open and then close
        out.close();
        in.close();
    }
}    

                      //1. Creating source-only plain text for characters
        File src=new File("f:/char.txt");
        File dest=new File("f:/testIO/char.txt");
        //2. Selective flow
    BufferedReader reader=new BufferedReader(new FileReader(src));
BufferedWriter wr=new BufferedWriter(new  FileWriter(dest,true));pend(msg2); 
                     //3. New Method Operation
        String line=null;
        while(null!=(line=reader.readLine())){
            wr.write(line);
            //wr.append("\r\n");
            //newline
            wr.newLine();
        }
        wr.flush();//Forced brush out
// 4. Turn off the flow first and then close it
        out.close();
        in.close();

4. Transform processing flow: Output Stream Writer

The character set of a file can be processed, that is, the file is encoded and stored according to the specified character set.

//Write out the file code
BufferedWriter bw=new BufferedWriter(
    new OutputStreamWriter(
        new BufferedOutputStream(
            new FileOutputStream(
                new File("f:/testIO/char.txt")
            )
        ),"utf-8"
    )
);
    String info=null;
    while(null!=(info=br.readLine())){
        bw.write(info);
        bw.newLine();
    }
    bw.flush();
    bw.close();

5. ByteArray OutputStream Node Class

/**
* Byte Array Output Stream: Operations are somewhat different from file output streams. There are new methods, so polymorphism is not allowed.
* @throws IOException 
*/
    public static byte[] write() throws IOException{
        //Destination byte array
        byte[]dest;
    //Selection flow difference: No need to put the destination into new ByteArrayOutputStream()
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
    //The operation is written out, which can be treated as writing local content to the server through a byte array
        String msg="Byte Array Input Stream: Operations are consistent with File Input Stream operations";
        byte[]info=msg.getBytes();
        //Write content to bos
        bos.write(info,0,info.length);
    //The difference: Getting data to ByteArray (): Converting the output stream of byte arrays to byte arrays
        dest=bos.toByteArray();
        //Releasing resources
        bos.close();//Because bos are in the jvm, closing does not affect
        return dest;
    }
  

Let's look at a few more homework questions. You might as well think about them.
1. What are the basic characteristics of Reader and Writer?
2. What are the roles of FileReader and FileWriter?
3. What are the functions of Buffered Reader and Buffered Writer?
4. Can word documents use character stream operation? Why?
5. Using BufferedReader and BufferedWriter to Realize Copy of Text Files
6. Under what circumstances can you use character stream copy folders? Under what circumstances can't we? Should copy folders use character or byte streams?
7. What streams are used for copying files?
8. The role of Input Stream Reader and Output Stream Writer.
9. What are the data sources of Byte Array Input Stream and Byte Array Output Stream?
10. Why does Byte Array Output Stream not recommend anonymity?
11. Write "the knowledge that you believe you can't learn, only the knowledge you don't want to learn" into the byte array.
12. Read the string from the above byte array.
13. What are the characteristics of Data Input Stream and Data Output Stream?
14. Write 3.14 out into the byte array and read it
15. What does serialization and deserialization mean?
16. To serialize an object of a class, must the class implement the Serializable interface?
17. Talk about the characteristics of Serializable interface.
18. What is the role of transient s?
19. Use ObjectInputstream and ObjectOutputStream to store an object on the hard disk and then read it into the program.
20. What is the common use of PrintStream print streams?

Topics: Java jvm