[英]Optimizing BufferedReader for large input in java
I am trying to read a single line which is about 2 million characters long from the standard input using the following code: 我正在尝试使用以下代码从标准输入中读取一行大约200万个字符的行:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();
For the aforementioned input, the s = in.readLine();
对于上述输入,
s = in.readLine();
line takes over 30 minutes to execute. 行需要30分钟以上才能执行。
Is there a faster way of reading this input? 有没有读取此输入的更快方法?
Don't try to read line by line but try to read a buffer of characters instead 不要尝试逐行读取,而是尝试读取字符缓冲区
Try something like this 试试这个
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream("your-file"));
byte[] data = new byte[1024];
int count = 0;
while ((count = in.read(data)) != -1) {
// do what you want - save to other file, use a StringBuilder, it's your choice
}
} catch (IOException ex1) {
// Handle if something goes wrong
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ) {
// Handle if something goes wrong
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.