[英]Modify stream reader class to read from file instead of System.in
从文件读取时,我在时间上存在问题,因为在这种情况下使用的是扫描仪。 我有一个快速输入代码,但没有使用文件,因此我想向文件中添加文件或向我推荐使用文件的快速输入法
public class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
如注释中所建议,您可以通过向构造函数添加一个允许注入任何InputStream
的参数来修改类以处理文件输入:
public FastReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
然后,您可以按以下方式使用阅读器:
FastReader systemInReader = new FastReader(System.in);
FastReader fileReader = new FastReader(new FileInputStream("/path/to/the/file"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.