Can someone provide a template to perform really fast I/O using java as many problems require it?
For all of those who want answer, I found the following. It is from a submission by Egor .
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
outputStream)));
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine(int i) {
writer.println(i);
}
}
class IOUtils {
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++)
array[i] = in.readCharacter();
return array;
}
public static char[][] readTable(InputReader in, int rowCount,
int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readCharArray(in, columnCount);
return table;
}
}
class ArrayUtils {
public static void fill(int[][] array, int value) {
for (int[] row : array)
Arrays.fill(row, value);
}
}
class MiscUtils {
public static final int[] DX4 = { 1, 0, -1, 0 };
public static final int[] DY4 = { 0, -1, 0, 1 };
public static boolean isValidCell(int row, int column, int rowCount,
int columnCount) {
return row >= 0 && row < rowCount && column >= 0
&& column < columnCount;
}
}