Java Basics 19 BufferedReader class, Scanner, object serialization
“This is the 19th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”.
About the author
- The authors introduce
🍓 Blog home page: author’s home page 🍓 Introduction: 🥇, a high quality creator in JAVA field, 🎓, a junior in college, participated in various provincial and national competitions and won a series of honors. 🍓 pay attention to me: pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻.
BufferedReader class
BufferedReader belongs to a buffered input stream and is an operation object of a character stream. But it’s important to remember that there are two types of cache stream definitions for us: BufferedInputStream and BufferedReader.
If you want to put all the input data together and read it all at once, then you can definitely avoid the Chinese problem, and this operation must be done by the buffer operation stream. BufferedInputStream and BufferedReader are defined in the IO package, but the BufferedReader class must be used for this operation. The BufferedReader class has its own inheritance structure, constructor, and operation methods:
Inheritance structure: | java.lang.Object java.io.Reader java.io.BuffereedReader |
---|---|
Construction method: | public BuffereedReader(Reader in) |
Read operation: | public String readLine() throws IOException |
We chose the readLine() method provided by the BufferReader class operation, which reads a line of data using a carriage return.
Use BufferedReader to read data
package com.day15.demo;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BufferReaderDemo {
public static void main(String[] args) throws Exception{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter");
// The default newline mode is the biggest drawback of BufferReader
String str = bufr.readLine();// Accepts input information. By default, carriage return is usedSystem.out.println(str); }}Copy the code
Verify the input data to determine whether it is a number
package com.day15.demo;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BufferReaderDemo {
public static void main(String[] args) throws Exception{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter your age");
// The default newline mode is the biggest drawback of BufferReader
String str = bufr.readLine();// Accepts input information. By default, carriage return is used
if(str.matches("\ \ d {1, 3}"))
System.out.println(str);
else
System.out.println("Incorrect input data!"); }}Copy the code
Scanner
This class appears as a utility class that defines two of the following methods in Scanner:
public Scanner(InputStream sourse); | A constructor |
---|---|
public Boolean hasNextXxx(); | Determine if there is data |
Public Data type nextXxx(); | To obtain data |
public Scanner useDelimiter(String partern); | Defining delimiters |
Future calls must first use hasNextXxx() to determine whether data in the specified format is present before executing nextXxx().
Enter data using the Scanner class
package com.day15.demo;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter data:");
if(sc.hasNext()){// Now there is input, cannot judge empty stringSystem.out.println(sc.next()); } sc.close(); }}Copy the code
Use the Scanner class to determine if the input data is an int
package com.day15.demo;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
System.out.println("Please enter data:");
Scanner sca=new Scanner(System.in);
if(sca.hasNextInt()){
int date=sca.nextInt();
System.out.println("The input data is:"+date);
}else{
System.out.println("The input is not a number."); }}}Copy the code
In the Scaner class, the input to the useDelimiter() method is for strings, but the other data types are not easy to use.
Use the Scanner class to determine if the user entered a birthday
package com.day15.demo;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter date of birth:");
if(sc.hasNext("\\d{4}-\\d{2}-\\d{2}")) {// Now there is input, cannot judge empty string
String bir = sc.next("\\d{4}-\\d{2}-\\d{2}"); System.out.println(bir); } sc.close(); }}Copy the code
Scanner Reads the contents of a file
package com.day15.demo;
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(new FileInputStream(new File("f:" + File.separator + "test" + File.separator + "hello.txt")));
sc.useDelimiter("\n");
if(sc.hasNext()){// Now there is input, cannot judge empty stringSystem.out.println(sc.next()); } sc.close(); }}Copy the code
In addition to the binary file copy processing, as long as the output of information for the program is a print stream, the information input is Scanner.
Object serialization
All projects must have a concept of serialization.
The concept of object serialization
Object serialization refers to transferring an object stored in memory as a binary stream or storing it in text. However, we do not mean that all objects can be serialized. Strictly speaking, the class objects we need to instantiate often need to be transported, and the class must implement the Java.io.Serializable interface. But this interface doesn’t have any method definitions, so it’s just an identifier.
package com.day15.demo;
import java.io.Serializable;
class Person implements Serializable{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge(a) {
return age;
}
public void setAge(int age) {
this.age = age; }}public class SerializableDemo {}Copy the code
The serialized object is what you need to store is the properties in the object so by default the properties of the object will be stored as binary data stream.
Implement serialization and deserialization
ObjectOutputStream, ObjectInputStream, ObjectOutputStream, ObjectOutputStream
ObjectOutputStream | ObjectInputStream |
---|---|
java.lang.Object java.io.OutputStream java.io.ObjectOutputStream |
java.lang.Object java.io.InputStream java.io.ObjectInputStream |
public ObjectOutputStream(OutputStream out) throws IOException |
public ObjectInputStream(InputStream in) throws IOException |
public final void writeObject(Object obj) throws IOException |
public final Object readObject() throws IOException,ClassNotFoundException |
Implements serialization of objects
package com.day15.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
class Person implements Serializable{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge(a) {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString(a) {
return "Person [name=" + name + ", age=" + age + "]"; }}public class SerializableDemo{
public static final File FILE = new File("F:" + File.separator + "test" + File.separator + "person.txt");
public static void ser(Object o) throws Exception {
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(FILE));
outputStream.writeObject(o);
outputStream.close();
}
public static void dser(a) throws Exception {
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(FILE));
System.out.println(inputStream.readObject());
inputStream.close();
}
public static void main(String[] args) throws Exception{
/ / the serialization
//ser(new Person(" zhang ",20));
// deserializedser(); }}Copy the code
The main reason why com.day15.demo.Person@6d311334 occurs is because the entity class did not override the toString() method.
Transient keywords (understand)
There are actually two classes of serialization in Java.io, and Serializable is the most widely used serialization interface. This is done in an automated mode, with all attributes being serialized by default. There is an Externalizable interface that requires manual serialization by the user.
Serializable saves all attributes in an object by default, but if you don’t want to save some attributes now, you can use the TRANSIENT keyword.
Using transient
package com.day15.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
class Person implements Serializable{
private transient String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge(a) {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString(a) {
return "Person [name=" + name + ", age=" + age + "]"; }}public class SerializableDemo{
public static final File FILE = new File("F:" + File.separator + "test" + File.separator + "person.txt");
public static void ser(Object o) throws Exception {
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(FILE));
outputStream.writeObject(o);
outputStream.close();
}
public static void dser(a) throws Exception {
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(FILE));
System.out.println(inputStream.readObject());
inputStream.close();
}
public static void main(String[] args) throws Exception{
ser(new Person("Pockmarked zhang".20)); dser(); }}/*
Person [name=null, age=20]
*/
Copy the code
Name is not serialized. Serialization is often used on simple Java classes, and is rarely used on other classes, but transient is rarely used on simple Java classes.