Shang Xuetang__ Baizhan programmer__ Question 1573 ------ Chapter 9 IO stream technology

Posted by mcog_esteban on Mon, 20 Dec 2021 04:21:34 +0100

1. What does IO mean? What does data source mean?

        Input,Output; Input and output

Data source: data source

2. What is the difference between byte stream and character stream? What is the difference between an input stream and an output stream?

Character stream and byte stream are a division of stream, which are divided according to the data unit of processing stream.

Both types are divided into input and output operations. OutputStream is mainly used to output data in byte stream,

InputStream is used for input, and Writer class is mainly used for output in character stream,

The input stream is mainly completed by using the Reader class. These four are abstract classes.

The unit of character stream processing is 2-byte Unicode characters, which operate characters, character arrays or strings respectively, while the byte stream processing unit is 1-byte, which operates bytes and byte arrays.

Byte stream is the most basic. All subclasses of InputStream and OutputStream are byte streams, which are mainly used to process binary data. It is processed by bytes.

However, in practice, a lot of data is text, and the concept of character stream is proposed. It is processed according to the coding of virtual machine, that is, to convert the character set. The two are associated through inputstreamreader and outputstreamwriter (conversion stream). In fact, they are associated through byte [] and String.

Flow is like a pipe. Between programs and files, the direction of input and output is for the program. Reading into the program is the input flow, and reading out from the program is the output flow. The input stream is the obtained data, and the output stream is the output data.

3. What is the difference between a node flow and a process flow?

Node flow and processing flow are another division of flow, which are divided according to different functions.

Node flow, which can read and write data from or to a specific place (node).

Processing flow is the connection and encapsulation of an existing flow, and data reading and writing are realized through the function call of the encapsulated flow.

Such as BufferedReader. The construction method of processing flow always takes another flow object as a parameter. A stream object is wrapped many times by other streams, which is called a stream link.

4. Can word documents use character stream operation? Why?

No. Because word document is not a plain text file, it contains a lot of format information in addition to text. Cannot operate with character stream. You can use byte stream operations.

5. [on Computer] complete the code of file data read in by the teacher in class:

        

public static void testReader(){
            File f = new File("d:a.txt");
        FileInputStream fils = null;
        try {
            fils = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int m = 0;
        try {
            while((m = fils.read())!= -1){
                char c = (char)m;
                System.out.println(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                if(fils != null){
                    fils.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

6. Explain the meaning of the following code

while((m=fis.read())!=-1){
char c = (char) m;
System.out.print(c);
}

The above example shows that fis is a byte input stream object, fis Read () reads one byte from the specified file at a time, and the return value is an integer of type int represented by this byte. If the end of the file is read (nothing is readable), then - 1 is returned.

The following code reads the file in turn, one byte at a time, and reads it circularly; After each reading, convert the returned integer value (m) into char type data (strong conversion) (so as to know what character is read each time), and output this character until it is read.

7. After the flow object is used, it is generally necessary to call the close method to close and release resources. Is this right?

Right

8. [on the computer] complete the operation of writing files by the teacher:

        

static void testWrite(){
        FileOutputStream fos = null;
        String str = "sffsdfsdfsdfsdfsdfsdfsdf";
        try {
            fos = new FileOutputStream("d:/b.txt");
                /*for(int i=0;i<str.length();i++){
                fos.write(str.charAt(i));
            }*/
            fos.write(str.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(fos!=null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

9. What are the basic characteristics of InputStream and OutputStream?

Both are abstract parent classes of [byte] input / output stream. Data is processed in bytes, one byte is read / written at a time. They are suitable for processing binary files, such as audio, video, pictures, etc. the implementation classes include FileInputStream and FileOutputStream.

10. What are the basic features of Reader and Writer?

Both are abstract parent classes of [character] input / output stream. Data is processed in character units, one character is read / written at a time. They are suitable for processing text files. Implementation classes include FileReader and FileWriter

11. What are the basic functions of FileInputStream and OutputStream?

Both are implementation classes of [byte] input / output stream, and their abstract parent classes are InputStream and OutputStream. Data is processed in bytes, and one byte is read / written to / from the specified file at a time. They are suitable for processing binary files, such as audio, video, pictures, etc.

12. What are the functions of FileReader and FileWriter?

Both of them are implementation classes of [character] input / output stream, and their abstract parent classes are Reader and Writer. They process data in character units and read / write one character to / from the specified file at a time. They are suitable for processing text files.

13. [on the computer] complete the copy code of the file

static void copyCode(){
    File file = new File("e:\\picture1.jpg");
    try (InputStream is = new FileInputStream(file)) {
        File file1 = new File("e\\picture2.jpg");
        OutputStream os = new FileOutputStream(file1);

        int b = 0;

        while((b = is.read())!= -1){
            os.write(b);
        }
        os.close();
        is.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

14. What are the characteristics of BufferInputStream and BufferedOutputStream?

15. [on the computer] use BufferedReader and BufferedWriter to copy text files.

16. What is PrintStream often used for? System. Is out a print stream?

17. [on Computer] realize the mutual conversion between byte array and any basic type and reference type

18. What are the characteristics of DataInputStream and DataOutputStream?

19. [on Computer] use ObjectInputstream and ObjectOutputStream to store an object
To the hard disk, and then read it into the program.

20. How is Chinese garbled code caused?

When reading and writing character stream, the coding method shall be set as required. If the coding method is not set properly, Chinese garbled code will appear.

21. How many bytes does the unicode character set represent a character? Why utf-8?

Two bytes in the Unicode character set represent one character.

Reference: https://blog.csdn.net/jlfw/article/details/6384057 Why utf-8

22. What does serialization and deserialization mean?

1) serialization:
Write the object to the file in the form of byte stream - > serialization;
The class of the object to be serialized implements the Serializable interface:
        publicclassUserimplements Serializable {
/ / omitted;
        }
The User implements this interface. The object representing the User class has the function of writing the object into the file in the form of byte stream.

(2) deserialization:
Reading the data in the file into the program in the form of byte stream is still an object deserialization.

23. If you want to serialize an object of a class, must the class implement the Serializable interface?

The objects to be sequenced must implement the Serializable interface to enable serialization.

24. Talk about the characteristics of Serializable interface.

1. The class of the object to be serialized must implement the Serializable interface.
2. Add a serialization number to the class, that is, define a tag for the class, such as:
public static final long serialVersionUID=1L;
The new modified class can also manipulate objects that have been serialized.
3. Static cannot be serialized,
Serialization can only serialize objects in the heap, not objects in the method area.
4. Fields that do not need to be serialized are preceded by transient, such as:
private transient String password;

25. What is the function of transient?

For attributes that do not want to be serialized, you can add the transient keyword;
The password field is a very sensitive field. When serializing, it is not allowed to write to the file:
private transient String password;

26. [on the computer] complete the copy code of the directory (combined with recursive algorithm)

        

 /**
     * CopyDocJob Defines the tasks actually performed, i.e
     * Copy files from the source directory to the destination directory
     */
    public static void main(String[] args) throws IOException {
        copyDirectiory("d:/301sxt","d:/301sxt2");
    }
    /**
     * Copy a single file
     * @param sourceFile source file
     * @param targetFile Target file
     * @throws IOException
     */
    private static void copyFile(File sourceFile,File targetFile)throws IOException{
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
// New file input stream
        inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
// New file output stream
        outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

//        Buffer array
        byte[] b = new byte[1024 * 5];
        int len;
        while((len = inBuff.read(b))!= -1){
            outBuff.write(b,0,len);
        }
//        Flush buffered output stream
        outBuff.flush();

        if(inBuff != null){
            inBuff.close();
        }
        if(outBuff != null){
            outBuff.close();
        }
    }
    /**
     * duplicate catalog
     * @param sourceDir Source directory
     * @param targetDir Target directory
     * @throws IOException
     */
    private static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
//        Check source directory
        File fSourceDir = new File(sourceDir);
        if(!fSourceDir.exists() || !fSourceDir.isDirectory()){
            return ;
        }
//        Check the target directory and create it if it does not exist
        File fTargetDir = new File(targetDir);
        if(!fTargetDir.exists()){
            fTargetDir.mkdirs();
        }
//        Traverse the files or directories under the source directory
        File[] file = fSourceDir.listFiles();
        for (int i = 0; i < file.length; i++) {
            if(file[i].isFile()){
//                source file
                File sourceFile = file[i];
//                Target file
                File targetFile = new File(fTargetDir,file[i].getName());
                copyFile(sourceFile,targetFile);
            }
//            Recursively copy subdirectories
            if(file[i].isDirectory()){
//                Source folder ready for replication
                String subSourceDir = sourceDir + File.separator+file[i].getName();
//                Destination folder ready for replication
                String subTargetDir = targetDir + File.separator + file[i].getName();
                copyDirectiory(subSourceDir,subTargetDir);
            }
        }
    }

27. [on the computer] it is assumed that all written Java codes are in the d:/sxtjava folder since enrollment, including multiple

Level subfolders. Use IO stream to get how many lines of Java code have been written since enrollment.

class CountDir{
    private int count;
    /**
     * Count the number of lines in a java file
     */
    private void countLine(File sourceFile) throws IOException {
        BufferedReader br = null;

        try {
            br = new BufferedReader(new FileReader(sourceFile));
            while (br.readLine() != null){
                count++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            br.close();
        }
    }
    /**
     * Count the number of lines of all Java files in a directory
     */
    private void countDir(String sourceDir) throws IOException {
//        Check source directory
        File fSourceDir = new File(sourceDir);
        if(!fSourceDir.exists() || !fSourceDir.isDirectory()){
            System.out.println("The source directory does not exist");
            return;
        }

//        Traverse the files or directories under the directory
        File[] file = fSourceDir.listFiles();
        for (int i = 0; i < file.length; i++) {
            if(file[i].isFile()){
                if(file[i].getName().toLowerCase().endsWith(".java")){
                    countLine(file[i]);
                }
            }
//            Recursive statistics of code lines
            if(file[i].isDirectory()){
                String subSourceDir = sourceDir + File.separator + file[i].getName();
//                Statistics subdirectory
                countDir(subSourceDir);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        CountDir tcd = new CountDir();
        tcd.countDir("d:/java");
        System.out.println(tcd.count);
    }
}

28. [on the computer] download and self-study the IO toolkit in apache commons.

Take a look at this blog post if you are interested!

https://www.cnblogs.com/softidea/p/4279576.html

Topics: JavaSE