java蓝桥杯bufferedReader和Writer封装

每次都得定义bufferedreader和writer太麻烦了,并且每次使用的时候,还需要一行一行的读,之后转化成int,实在是麻烦的离谱。写一个输入输出,可以scanner一样使用nextInt()和netxtLine()进行读取。

package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class InAndOutUitl {
    
    
//	private static Scanner sc = new Scanner(System.in);
	private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	private static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
	private int curn;
	private int[] curLine;
	public InAndOutUitl(){
    
    
		// TODO Auto-generated constructor stub
		curn = -1;
	}
	
	public String nextLine() throws Exception {
    
    
		return in.readLine();
	}
	/**将一行转化成数组*/
	public int[] toIntArray(String s) {
    
    
		String[] input = s.split(" ");
		int[] ans = new int[input.length];
		for (int i = 0; i < input.length; i++) {
    
    
			ans[i] = Integer.parseInt(input[i]);   
		}
		return ans;
	}
	/**
	 * 
	 * 如果输入终止返回空。
	 * */
	public Integer nextInt() throws Exception{
    
    
		// 新的一行
		if (curn == -1) {
    
    
			curn = 0;
			String tmp = in.readLine();
			if (tmp == null) return null;
			curLine = toIntArray(tmp);
		}
		int ans = curLine[curn++];
		// 读完这一行指针指向下一行
		if (curn == curLine.length) curn = -1;
		return ans;
	}
	// 输出
	public void write(String s) throws Exception {
    
    
		out.write(s);
	}
	// 挤缓冲
	public void flush() throws Exception {
    
    
		out.flush();
	}

}


猜你喜欢

转载自blog.csdn.net/fuzekun/article/details/129896279