48-input and output support

Input and output support

  If you want to realize the output of the content through the program, the core essence must be completed through the OutputStream class. The biggest disadvantage of this class is the limited data output function. ( public void write(byte[] b) throws IOException), all data must be converted to byte arrays before they can be output. Suppose that the current project may output long, double, and Date. In this case, these data must be converted into byte form. Processing, such processing is more troublesome. Initially, in order to solve this kind of repetitive operation, developers often define some functional classes themselves to simplify the output process.

Print stream

Print flow design ideas

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

class PrintUtil implements AutoCloseable{
    
    		//实现常用数据输出
	private OutputStream output; 		//不管现在如何操作,核心就是使用OutputStream
	public PrintUtil(OutputStream output) {
    
    		//由外部决定输出的位置
		this.output = output;
	}
	public void println(long num) {
    
    
		this.println(String.valueOf(num));
	}
	public void print(long num) {
    
    
		this.print(String.valueOf(num));
	}
	public void print(String str) {
    
    		//输出字符串
		try {
    
    
			this.output.write(str.getBytes());
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}		//输出
	}
	public void println(String str) {
    
    
		this.print(str + "\r\n");
	}
	@Override
	public void close() throws Exception {
    
    
		this.output.close();
	}
}

public class Introduce {
    
    
	public static void main(String[] args) throws Exception {
    
    
		File file = new File("C:\\Project\\Java_study\\src\\文件\\test.txt");
		PrintUtil pu = new PrintUtil(new FileOutputStream(file));
		pu.println("name:lyz");
		pu.print("age:");
		pu.print(78);
		pu.close();
	}
}

  The essence of the design idea of ​​the print stream during the entire operation is to improve the functions of the existing classes. For example: OutputStream is the only standard operation class that can realize output. It should be the core fundamental, but the operation functions of this class are limited, so It is inconvenient to output each data type, so a layer of packaging is made for it, so the design idea adopted at this time is the "decorative design pattern".
  But since all developers have discovered the deficiencies of the original OutputSteam function, designers can definitely find out, so in order to solve the output problem, the java.io package provides print streams: PrintStream, PrintWriter.
y8kt2R.png

PrintStream PrintWriter
public class PrintStream extends FilterOutputStrem implements Appendable,Closeable public class PrintWriter extends Writer
构造:public PrintStream(OutputStream out) 构造:public PrintWriter(OutputStream out/Writer out)

  Use PrintWriter to realize data output operation
data output

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class Introduce {
    
    
	public static void main(String[] args) throws Exception {
    
    
		File file = new File("C:\\Project\\Java_study\\src\\文件\\test.txt");
		PrintWriter pu = new PrintWriter(new FileOutputStream(file));
		pu.println("name:33333");
		pu.print("age:");
		pu.print(78);
		pu.close();
	}
}

  Since JDK1.5, the PrintWriter class has added operation support for formatted output : public PrintWriter printf(String format,Object... args);
formatted output

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class Introduce {
    
    
	public static void main(String[] args) throws Exception {
    
    
		File file = new File("C:\\Project\\Java_study\\src\\文件\\test.txt");
		PrintWriter pu = new PrintWriter(new FileOutputStream(file));
		String name = "ly";
		int age = 18;
		double salary = 7812.23;
		pu.printf("name:%s,age:%d,salary:%9.2f", name,age,salary);
		pu.close();
	}
}

  Compared to directly using the OutputStream class, the processing operations using the PrintWriter and PrintStream classes will be easier. In the future, as long as the program outputs content, all print streams are used.

System class support for IO

  System is a system class, and it is a system class that has been used from beginning to end. Three constants are provided in this class:

  • Standard output (display):public static final PrintStream out;
  • Error output:public static final PrintStream err;
  • Standard input (keyboard):public static final InputStream in;

  System.out and System.err are both of the same type. If System.err is used for output, it will use red font, while System.out will use black font.
  The first operation of setting two outputs is purposeful. System.out outputs the information that the user wants to see, and System.err outputs the information that the user does not want to see. You can also modify the output location if necessary:

  • Modify the output location of out:public static void setOut(PrintStream out);
  • Modify the output location of err:public static void setErr(PrintStream err);

Modify System.err location

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class System_IO {
    
    

	public static void main(String[] args) throws Exception {
    
    
		System.setErr(new PrintStream(new FileOutputStream(new File("C:\\Project\\Java_study\\src\\文件\\test.txt"))));
		try {
    
    
			Integer.parseInt("a");
		} catch (Exception e) {
    
    
			System.out.println(e);
			System.err.println(e);		//输出到文件
		}
	}
}

  An in constant is also provided in the System class. This constant corresponds to the input processing of the standard input device keyboard, which can realize keyboard data input.
Realize keyboard input

import java.io.InputStream;

public class System_IO {
    
    

	public static void main(String[] args) throws Exception {
    
    
		InputStream input = System.in;
		System.out.println("输入信息:");
		byte[] data = new byte[1024];
		int len = input.read(data);
		System.out.println(new String(data,0,len));
	}
}

  Such keyboard input processing itself is flawed: if the current receptionInsufficient array length, Then only part of the data can be received, so this input needs to repeat the input stream data reception. And it may also be involvedInput ChineseIn the case of improper handling of Chinese, garbled characters may occur.

BufferedReader buffered input stream

  The BufferedReader class provides the concept of a buffered character input stream, that is, the use of the BufferedReader class can solve the problem of reading input stream data. This class is the most complete input processing provided at the beginning (JDK1.5 Before 1.5, a more powerful class appeared). The reason for using this class is because this class provides an important method:

  • Read a row of data:public String readLine() throws IOException;

yYrHkn.png
Use this class to realize the standardized definition of keyboard input data

import java.io.InputStreamReader;

public class BufferedReader {
    
    

	public static void main(String[] args) throws Exception {
    
    
		java.io.BufferedReader input = new java.io.BufferedReader(new InputStreamReader(System.in));
		System.out.println("请输入信息:");
		String msg = input.readLine();		//接收输入
		System.out.println("输入内容:"+ msg);
	}
}

  In the future, the actual development process will often encounter the situation of input data, and all types of input data are described by String, which facilitates the receiver to perform various processing.
Accept integer input and verify

import java.io.InputStreamReader;

public class BufferedReader {
    
    

	public static void main(String[] args) throws Exception {
    
    
		java.io.BufferedReader input = new java.io.BufferedReader(new InputStreamReader(System.in));
		System.out.println("请输入age:");
		String msg = input.readLine();		//接收输入
		if(msg.matches("\\d+{1,3}")) {
    
    		//是否由数字组成
			int age = Integer.parseInt(msg);
			System.out.println("age:"+age);
		} else {
    
    
			System.out.println("输入错误!");
		}
	}
}

  For modern Java development, there are not many cases where data is input by keyboard. The standard method of keyboard input (JDK1.5) is the implementation of the above operation. In actual development, all input data is a string, which is convenient for users to verify and string Complex processing.

Scanner scan stream

  java.util.Scanner is a program class added after JDK1.5. Its main purpose is to solve the input stream access problem. It can be understood as an alternative function class for BufferedReader. The Scanner class has the following operation methods:

  • structure:public Scanner(InputStream source);
  • Determine whether there is data:public boolean hasNext();
  • Take out the data:public String next();
  • Set the separator:public Scanner useDelimiter(String pattern);

Use Scanner to realize keyboard data input

import java.util.Scanner;

public class Scanner_Study {
    
    

	public static void main(String[] args) {
    
    
		Scanner scan = new Scanner(System.in);
		System.out.println("input age:");
		if(scan.hasNextInt()) {
    
    
			System.out.println("age:"+ scan.nextInt());
		} else {
    
    
			System.out.println("get out!");
		}
		scan.close();
	}
}

Use Scanner to input string

import java.util.Scanner;

public class Scanner_Study {
    
    

	public static void main(String[] args) {
    
    
		Scanner scan = new Scanner(System.in);
		System.out.println("msg:");
		if(scan.hasNext()) {
    
    
			System.out.println("msg:"+ scan.next());
		} else {
    
    
			System.out.println("get out!");
		}
		scan.close();
	}
}

  There is another biggest feature of using Scanner to input data, which can be directly used for verification and judgment.
Enter a birthday to verify

import java.text.SimpleDateFormat;
import java.util.Scanner;

public class Scanner_Study {
    
    

	public static void main(String[] args) throws Exception {
    
    
		Scanner scan = new Scanner(System.in);
		System.out.println("birthday:");
		if(scan.hasNext("\\d{4}-\\d{2}-\\d{2}")) {
    
    
			// String str = scan.next();
			System.out.println("msg:"+ new SimpleDateFormat("yyyy-MM-dd").parse(scan.next()));
		} else {
    
    
			System.out.println("get out!");
		}
		scan.close();
	}
}

  It can be found that the overall design of Scanner is better than BufferedReader, and it is more convenient than using InputStream directly. If you use InputStream to read all the content information in a text file, you must rely on the memory output stream for temporary data storage and you need to determine whether the content is a newline.

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class Scanner_Study {
    
    

	public static void main(String[] args) throws Exception {
    
    
		Scanner scan = new Scanner(new File("C:\\Project\\Java_study\\src\\文件\\test.txt"));
		scan.useDelimiter("\n");		//设置读取分隔符
		while(scan.hasNext()) {
    
    
			System.out.println(scan.next());
		}
		scan.close();
	}
}

  In the future, the program needs to use PrintWriter for output data, and Scanner or BufferedReader for input data.

Guess you like

Origin blog.csdn.net/MARVEL_3000/article/details/114439320