Last active
February 25, 2019 15:42
-
-
Save Arham4/9231893d1d9e70434fa285e952f08eed to your computer and use it in GitHub Desktop.
Faster file/keyboard input reader that allows for the ease of use of Scanner coupled with the efficiency of BufferedReaders and StringTokenizers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.InputMismatchException; | |
import java.util.StringTokenizer; | |
public final class FastReader { | |
private BufferedReader bufferedReader; | |
private StringTokenizer stringTokenizer; | |
public FastReader() { | |
bufferedReader = new BufferedReader(new InputStreamReader(System.in)); | |
} | |
public FastReader(String fileName) { | |
try { | |
bufferedReader = new BufferedReader(new FileReader(fileName)); | |
} catch (FileNotFoundException fnfe) { | |
fnfe.printStackTrace(); | |
} | |
} | |
public String next() { | |
while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { | |
try { | |
stringTokenizer = new StringTokenizer(bufferedReader.readLine()); | |
} catch (IOException ie) { | |
ie.printStackTrace(); | |
} catch (NullPointerException npe) { | |
return null; | |
} | |
} | |
return stringTokenizer.nextToken(); | |
} | |
public int nextInt() { | |
try { | |
return Integer.parseInt(next()); | |
} catch (NumberFormatException nfe) { | |
throw new InputMismatchException(nfe.getMessage()); | |
} | |
} | |
public String nextLine() { | |
String line = ""; | |
try { | |
line = bufferedReader.readLine(); | |
} catch (IOException ie) { | |
ie.printStackTrace(); | |
} | |
return line; | |
} | |
public boolean hasNextLine() { | |
return hasNextString(nextLine()); | |
} | |
public boolean hasNext() { | |
return hasNextString(next()); | |
} | |
private boolean hasNextString(String input) { | |
if (input != null) { | |
stringTokenizer = new StringTokenizer(input); | |
return true; | |
} | |
return false; | |
} | |
public boolean hasNextInt() { | |
String next = next(); | |
if (next != null) { | |
stringTokenizer = new StringTokenizer(next); | |
try { | |
Integer.parseInt(next); | |
return true; | |
} catch (NumberFormatException nfe) { | |
return false; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment