Small details of the IO stream (very small, very important)

IO stream in Java (one):
https://blog.csdn.net/Veer_c/article/details/103833045
IO stream in Java (2):
https://blog.csdn.net/Veer_c/article/details/103833423
IO Stream in Java (3):
https://blog.csdn.net/Veer_c/article/details/103833811

LineNumberReader:
public int getLineNumber(): Get the line number
Public void setLineNumber: Set the starting line number
String readLine(): Read a line
Note: If you do not set a line number, the default starts at 0. If you set a line number, it starts at the set line number.
Case study: Read a file, print one line at a time, and add line numbers

package com.edu_01;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class LineNumberReaderDemo {
    public static void main(String[] args) throws IOException {
        //Create LineNumberReader object
        //public LineNumberReader(Reader in)
        LineNumberReader lnr = new LineNumberReader(new FileReader("a.txt"));
        //Default starting line number starts at 0
        //Read one line at a time
        String line;
        while ((line = lnr.readLine())!=null) {
            //Print the line number and contents of each line
            System.out.println(lnr.getLineNumber()+":"+line);
        }
        //Shutdown
        lnr.close();
    }
}

Operating streams of basic data types
Basic types of stream objects can be manipulated.
DataInputStream: Read Data
DataOutputStream: Write data
Note: The order of reading and writing must be the same, that is, what type of data you write and what type of data you must use to read when you write data to a file, otherwise errors will occur.
Case: Write basic types of data to the stream and read it.

public class DataOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        //Write data
        //write();
        read();
    }
    private static void read() throws IOException {
        //DataInputStream: Read Data
        //Create object: public DataInputStream(InputStream in)
        DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));
        //Read the data, write in what order you must read it
        System.out.println(dis.readByte());
        System.out.println(dis.readShort());
        System.out.println(dis.readInt());
        System.out.println(dis.readLong());
        System.out.println(dis.readChar());
        System.out.println(dis.readFloat());
        System.out.println(dis.readDouble());
        System.out.println(dis.readBoolean());
        //Shutdown
        dis.close();
    }
    private static void write() throws IOException {
        //public DataOutputStream(OutputStream out)
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));
        //Write basic types of data to streaming associated files
        dos.writeByte(20);
        dos.writeShort(200);
        dos.writeInt(2000);
        dos.writeLong(20000L);
        dos.writeChar(97);
        dos.writeFloat(12.34F);
        dos.writeDouble(23.34);
        dos.writeBoolean(true);
        //Shutdown
        dos.close();
    }
}

Memory operation stream: Solves temporary data storage problems.
Operate on byte arrays (just demonstrate one case)
ByteArrayInputStream
ByteArrayOutputStream
byte[] toByteArray() converts a stream previously written to memory into an array of bytes
Note: When writing to a file, the file is written directly into memory. Writing can be done in different ways. When reading, the data written to the file must be encapsulated into an appropriate array so that it can be read out.
Array of operation characters
CharArrayReader
CharArrayWrite
Action String
StringReader
StringWriter
Operational Byte Array
ByteArrayInputStream
ByteArrayOutputStream
Write data to stream, save it in memory, and read it

package com.edu_03;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteArrayOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        //Write data in memory to public ByteArrayOutputStream()
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //Write data to in-memory calling methods
        baos.write("hello".getBytes());
        //Read data written to memory
        byte[] buf = baos.toByteArray();//Call this method to store previously written data in memory in a byte array
        ByteArrayInputStream bais = new ByteArrayInputStream(buf);//Associate bais with the contents just stored in the byte array
        //Only then can we read what we want directly from bais
        //Read one byte at a time
        int by;
        while ((by=bais.read())!=-1) {
            System.out.print((char)by);
        }
        //Shutdown
        bais.close();
        baos.close();
    }
}

Print stream:
Byte PrintStream PrintStream
Character Print Stream PrintWriter
Characteristic:
A: Only destinations, not data sources can be manipulated
B: Any type of data can be manipulated
C: Can automatically refresh if auto refresh is enabled
D: Streams that can manipulate files
Note: Streams that can be manipulated directly: Look at the API of the stream object, and if its construction method has both File and String type parameters, you can manipulate the file directly.
Case 1: Using a character print stream to write data in a file (String type) requires manual refresh.

package com.edu_04;
import java.io.IOException;
import java.io.PrintWriter;
public class PrintWriterDemo {
    public static void main(String[] args) throws IOException {
        //Writing hello,java,world to a file using a print stream
        //public PrintWriter(String fileName)
        PrintWriter pw = new PrintWriter("pw.txt");
        //Write data to stream associated files
        pw.write("hello");
        pw.write("java");
        pw.write("world");
        //Refresh
        pw.flush();
        //3. Shutdown
        pw.close();
    }
}

At this time, we did not turn on the automatic refresh function.
How to start automatic refresh: Using constructs
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(Writer out, boolean autoFlush)
boolean autoFlush: A parameter of type Boolean needs to be passed in to indicate that the automatic refresh has started when the parameter passed in is True.
If automatic refresh is enabled, this operation may only be completed if one of the methods of println, printf, or format is called.
println(): If automatic refresh is enabled, refresh can be achieved, and automatic line break can also be achieved.
Case 2: Start automatic refresh by using character stream to write data to file (int type, boolean type).

package com.edu_04;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class PrintWriterDemo2 {
    public static void main(String[] args) throws IOException {
        //Create a character print stream object and turn on automatic refresh
        //public PrintWriter(Writer out,boolean autoFlush)
        PrintWriter pw = new PrintWriter(new FileWriter("pw2.txt"), true);
        //Write data to stream
        //pw.write("hello");
        //pw.write("java");
        //Note: If automatic refresh is already enabled, you must call println, printf, or format to achieve automatic refresh
        pw.println("hello");
        pw.println("java");
        pw.println("world");//Call println to write data to the file, 1. Write data 2. Line break 3. Refresh
        //Can operate on any type of data
        pw.println(true);
        pw.println(12.34);
        //Shutdown
        pw.close();
    }
}

Emphasis: Automatic refresh requires two conditions:
1, must utilize
PrintWriter(OutputStream out, boolean autoFlush)
Construction method of PrintWriter(Writer out, boolean autoFlush)
2. Automatic refresh must be turned on when one of the methods of println, printf, or format is called
When one of the three methods above is called, the operation that he will complete is:
1. Write code 2. Line break 3. Auto refresh

Standard input-output stream
There are two member variables under the System class:
Standard input stream: public static final InputStream in
Standard Output Stream: public static final PrintStream out
Case 1: Keyboard input using label input stream, read stream after input and print to console

package com.edu_05;
import java.io.IOException;
import java.io.InputStream;
public class SystemIn {
    public static void main(String[] args) throws IOException {
        // public static final InputStream in  
        //Encapsulate data entered by keyboard into input stream
        //Scanner sc = new Scanner(System.in);
        InputStream is = System.in;
        //Read data entered by keyboard from input stream
        int by;
        while ((by=is.read())!=-1) {
            System.out.print((char)by);
        }
        //Shutdown
        is.close();
    }
}

Case 2: Keyboard entry using IO stream, reading one row at a time.
Analysis: Since we read one line at a time, we can BuffferedReader()
InputStream is = System.in;
At this point, the byte stream is read, and BufferedReader() needs the character stream, so the parameter passed in must be the character stream, so we need to convert the byte stream to the character stream InputStreamReader()

package com.edu_05;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SystemIn2 {
    public static void main(String[] args) throws IOException {
        /* Case 2: Keyboard entry using IO stream, reading one row at a time
         * InputStream is = System.in;
         * InputSreamReader isr = new InputStreamReader(is)
         * BufferedReader br = new BufferedReader(isr);   */
        //Write the above analysis as one
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        //Read one row at a time
        System.out.println("Please enter your name");
        String name = br.readLine();
        System.out.println("Please enter your age");
        String age = br.readLine();
        System.out.println(name+":"+age);
    }
}

Case: parse the output statement System.out.println("helloworld");

package com.edu_05;
import java.io.PrintStream;
/*  Standard Output Stream:
 *  public static final PrintStream out   */
public class SystemOut {
    public static void main(String[] args) {
//      PrintStream ps = System.out;
//      ps.println(true);
        //The above two lines are merged into one line, and the method in the byte print stream invoked at the bottom
        System.out.println(true);
    }
}

Note: The essence of this statement is that System has an out static field, so we can call the out field through System, return a standard output class, and then call the println() method to print the data

Merge Stream: The SequenceInputStream class can stream multiple input streams together into one input stream, so it is also known as a merge stream.
Construction:
SequenceInputStream(InputStream s1, InputStream s2): Combines S1 and S2 into one input stream, reading S1 before S2
Case 1:
I want to write DataStreamDemo.java and ByteArrayStreamDemo.java to a file, Copy.java
Data source:
DataStreamDemo.java
ByteArrayStreamDemo.java
Destination:
Copy.java
package com.edu_06;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
public class SequenceInputStreamDemo {
    public static void main(String[] args) throws IOException {
        //Create Merge Flow Object
        //SequenceInputStream(InputStream s1, InputStream s2): Combines S1 and S2 into one input stream, reading S1 before S2
        //Combine two data sources into one
        SequenceInputStream sis = new SequenceInputStream(new FileInputStream("PrintWriterDemo.java"), new FileInputStream("SystemIn2.java"));
        //Encapsulate Destination
        FileOutputStream fos = new FileOutputStream("copy2.java");
        //Read and write an array of bytes
        byte[] buf = new byte[1024];
        int len;
        while ((len=sis.read(buf))!=-1) {
            //How much to read and how much to write
            fos.write(buf, 0, len);
        }
        //Shutdown
        fos.close();
        sis.close();
    }
}

Serialization and Deserialization of Objects
Serialized Stream: Write objects to a file in the same way as the stream or transfer them over a network.
Deserialize streams: Restore streaming object data from a file or network.
ObjectOutputStream: Serialized Stream
WteObject (Object obj) writes the specified object to ObjectOutputStream.
ObjectInputStream: Deserialize Stream
Object readObject() reads an object from ObjectInputStream.

//1. Create a student class first
package com.edu_07;
import java.io.Serializable;
public class Studnet implements Serializable{
    //There is no way to implement this interface; it simply gives the Student class a serializable flag
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Studnet(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Studnet() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Studnet [name=" + name + ", age=" + age + "]";
    }
}
//2. Write objects into text using serialized streams
package com.edu_07;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class ObjectOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        //Create Serialized Stream Object
        //public ObjectOutputStream(OutputStream out)
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));
        //Create a student object and write it to a file
        Studnet s = new Studnet("Lau Andy", 50);
        oos.writeObject(s);
        // java.io.NotSerializableException
        //Class enables serialization by implementing the java.io.Serializable interface
        //Shutdown
        oos.close();
    }
}
//3. Read objects stored in files using deserialized streams
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ObjectInputStreamDemo {
    public static void main(String[] args) throws Exception {
        //Create Deserialized Stream Object
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));
        //Read objects stored in files for deserialization
        //readObject()
        Object object = ois.readObject();
        System.out.println(object);
        //Shutdown
        ois.close();
    }
}

Note: If a class does not implement the Serializable interface and cannot be instantiated, the exception java.io.NotSerializableException class is thrown to enable its serialization capabilities by implementing the java.io.Serializable interface.Classes that do not implement this interface will not be able to serialize or deserialize any of its states, so we can serialize the interface by having the class to which the object belongs.

Properties
The Properties:Properties class represents a persistent set of properties in which each key and its corresponding value is a string.
Features: Properties can be saved in or loaded from streams.
Case: Use the put method of a map collection to store data in the collection and traverse through it

package com.edu_08;
import java.util.Properties;
import java.util.Set;
public class ProppertiesDemo {
    public static void main(String[] args) {
        //Creating a Properties object is essentially a map number, but the key values are of type String
        Properties prop = new Properties();
        //Store elements in objects
        prop.put("zhangjie", "xiena");
        prop.put("huangxiaoming", "baby");
        prop.put("wanglaoshi", "zhangziyi");
        //map Collection Traversal
        //Get a collection of keys
        Set<Object> keys = prop.keySet();
        for (Object key : keys) {
            System.out.println(key+":"+prop.get(key));
        }
    }
}

Features of Properties:
Add Elements
public Object setProperty(String key,String value)
Get Elements
public String getProperty(String key)
public Set stringPropertyNames()
Case study: Use its special features to add elements and traverse

package com.edu_08;
import java.util.Properties;
import java.util.Set;
public class PropertiesDemo2 {
    public static void main(String[] args) {
        //Create the Properties collection
        Properties prop = new Properties();
        //Call public Object setProperty(String key,String value)
        prop.setProperty("huangxiaoming", "baby");
        prop.setProperty("dengchao", "sunli");
        prop.setProperty("libai", "wanglun");
        //1. Get a collection of all keys
        //public Set<String> stringPropertyNames()
        Set<String> keys = prop.stringPropertyNames();
        //Traverse keys to find values based on keys
        for (String key : keys) {
            System.out.println(key+":"+prop.getProperty(key));
        }
    }
}

Can be used in conjunction with IO streams:
Load data from a file into a collection.Note: The data in the file must be in the form of a key object (for example, String1=String2)
public void load(InputStream inStream)
public void load(Reader reader)
Case study: Create a key-value pair file, load the key-value pairs in the file into the set, and output the set

package com.edu_08;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
public class PropertiesDemo3 {
    public static void main(String[] args) throws IOException {
        //Create a collection
        Properties prop = new Properties();
        //Load key-value pairs from a file into a collection
        prop.load(new FileReader("prop.txt"));
        //Traverse Set
        Set<String> keys = prop.stringPropertyNames();
        for (String key : keys) {
            System.out.println(key+":"+prop.getProperty(key));
        }
    }
}

The data in the collection is stored in a text file and as key-value pairs.
public void store(OutputStream out,String comments)
public void store(Writer writer,String comments)
Case: Load the set of created key-value pairs into a file

package com.edu_08;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class PropertiesDemo4 {
    public static void main(String[] args) throws IOException {
        //Create a collection
        Properties prop = new Properties();
        //Store data in a collection
        prop.setProperty("liudehua", "50");
        prop.setProperty("liming", "60");
        prop.setProperty("zhangxueyou", "40");
        //Store elements in a collection in a text file
        prop.store(new FileWriter("prop2.txt"), "name=age");
    }
}

Case: I have a text file. I know the data is in the form of key-value pairs, but I don't know what it is.Write a program to determine if a key like "lisi" exists and change its value to "100" if it does.
Analysis:
1. We can load the text into the set and get the set of all keys
2. To determine if there is such a key in the set, if there is one, add such a key-value pair to the set again.
3. Finally, write the modified collection into the text

package com.edu_09;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
public class PropTest {
    public static void main(String[] args) throws IOException {
        /*           zhangsan=3
           lisi=4
           wangwu=5
           1.Create Collection Object
           2.Load key-value pairs from a file into a collection
           3.Get a collection of multiple keys, traverse, judge
           4.Restore key-value pair lisi=100 in the collection if Lisi exists
           5.Store data in a collection in a file   */
        //1. Create a collection object
        Properties prop = new Properties();
        // 2. Load key-value pairs from a file into a collection
        prop.load(new FileReader("prop3.txt"));
        //3. Get a collection of multiple keys, traverse, judge
        Set<String> keys = prop.stringPropertyNames();
        // 4. Restore the key-value pair lisi=100 in the collection if Lisi exists
        for (String key : keys) {
            if ("lisi".equals(key)) {
                prop.setProperty(key, "100");
            }
        }
        //5. Store the data in the collection in a file
        prop.store(new FileWriter("prop3.txt"), null);
    }

Case: I have a program for guessing a number Mini game. Please write a program that can only use more than five points in the test category to remind me that the game has ended, please pay.
Analysis:
1. First create a class that runs the game, note that it must be static, because only static can be called.
2. Create a text that contains count=1 and then load the text into the collection.
3. Then take out the text and get the count number of times.
4. Judgment, if the number of times is greater than 0, start the game, after each run, add one times, and then add to the collection.
5, load data from the collection into the text.

  // 1. Create a game class,
package com.edu_01;
import java.util.Scanner;
public class GuessNumber {
    public static void startGame(){
        int ran = (int) (Math.random()*100+1);
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("Please enter the number you guessed");
            int number = sc.nextInt();
            if (number>ran) {
                System.out.println("Big");
            }else if (number<ran) {
                System.out.println("Small");
            }else if (number==ran) {
                System.out.println("You guessed right");
                break;
            }
        }
    }
}
// 2. Create test classes
 package com.edu_01;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class PropTest {
    public static void main(String[] args) throws IOException {
        //1. Load key-value pairs from a file into a collection
        Properties prop = new Properties();
        prop.load(new FileReader("count.txt"));

        //2. Decide how many times you've played
        String count = prop.getProperty("count");
        //Convert String type to int type
        int number = Integer.parseInt(count);
        if (number>4) {
            System.out.println("Number has arrived, please pay");
        }else {
            //Open the game
            GuessNumber.startGame();
            number++;
            //Restore self-increasing times in files
            prop.setProperty("count", number+"");
            //Store the new prop collection in a file
            prop.store(new FileWriter("count.txt"), null);
        }
    }
}

IO stream (one):
https://blog.csdn.net/Veer_c/article/details/103833045
IO stream (2):
https://blog.csdn.net/Veer_c/article/details/103833423
IO stream (3):
https://blog.csdn.net/Veer_c/article/details/103833811

62 original articles were published. 55 were praised. 10,000 visits+
Private letter follow

Tags: Java network

Posted on Sat, 11 Jan 2020 21:15:51 -0500 by Johns3n