I am trying to read a single line which is about 2 million characters long from the standard input using the following code:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();
For the aforementioned input, the s = in.readLine();
line takes over 30 minutes to execute.
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
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.