处理IO的方式:
处理输入和输出的方式:
C++:cin / cout
Java:Scanner / System.out
但是这两种有超时的风险
那么C++处理方式:直接改为scanf / printf ,也就是C语言中的读写方式
Java处理方式:准备一个快读模板
下面就来介绍一下Java中的快读模板:
1.Scanner与System.out为什么慢?
输入输出的信息放在一个文件里,Scanner每次调用next()都需要访问IO设备,而且每次调用都只会取出去一个数,所以这样的速度就非常的慢,System.out也是同理的
2. 介绍解释Java快读的模板
Java处理IO有两套标准:
(1)字节流
(2)字符流:eg:带Reader的就是
BufferedReader的逻辑:(为什么快读快?)
它会先把放在文件中的数据全部放到内存缓冲区去,BufferedReader.next()的时候就直接到内存缓冲区拿数据
BufferedWriter也是一样的逻辑
模板代码:
import java.io.*;
import java.util.*;
public class Main {
//PrintWriter里面的方法和System.out的使用方法一样
public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static Read in = new Read();
public static void main(String[] args) throws IOException{
//写代码
int n = in.nextInt();
out.println(n);
out.close();
}
}
//快读模板
class Read {//自定义快读读入
//字符串裁剪
StringTokenizer st = new StringTokenizer("");
//1.字节流System.in->字符流InputStreamReader
//2.带内存缓冲区的字符流BufferedReader
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String next() throws IOException {
//为什么要while循环,因为可能读取的数据不止一行,有多行就需要多次取
while(!st.hasMoreTokens()) {
st = new StringTokenizer(bf.readLine());//先拿一行的数据
}
return st.nextToken();//对这一行的数据进行裁剪,拿到第一个数据
}
String nextLine() throws IOException {
return bf.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}