修改流 reader class 以从文件而不是 System.in 读取
Modify stream reader class to read from file instead of System.in
我在读取文件时遇到了问题,因为我在这种情况下使用了扫描仪。
我有一个代码快速输入但没有使用文件
所以我想在我的代码中添加一个文件,或者向我推荐一种使用 file
的快速输入法
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;
}
}
正如评论中所建议的那样,您可以修改 class 以通过向允许注入任何 InputStream
:
的构造函数添加参数来处理文件输入
public FastReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
然后你可以使用reader如下:
FastReader systemInReader = new FastReader(System.in);
FastReader fileReader = new FastReader(new FileInputStream("/path/to/the/file"));
我在读取文件时遇到了问题,因为我在这种情况下使用了扫描仪。 我有一个代码快速输入但没有使用文件 所以我想在我的代码中添加一个文件,或者向我推荐一种使用 file
的快速输入法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;
}
}
正如评论中所建议的那样,您可以修改 class 以通过向允许注入任何 InputStream
:
public FastReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
然后你可以使用reader如下:
FastReader systemInReader = new FastReader(System.in);
FastReader fileReader = new FastReader(new FileInputStream("/path/to/the/file"));