BufferedReader class
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | java.lang.Object | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | - | - | java.io.Reader | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | - | - | java.io.BufferedReader | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
Reads text from a character-input stream with buffer.
Revised from Open JDK source code
Create BufferedReader from System.in
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String strLine = in.readLine();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
out.write(strLine, 0, strLine.length());
out.flush();
in.close();
out.close();
}
}
Create BufferedReader from InputStreamReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Standard {
public static void main(String args[]) throws IOException {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String number;
int total = 0;
while ((number = cin.readLine()) != null) {
try {
total += Integer.parseInt(number);
} catch (NumberFormatException e) {
System.err.println("Invalid number in input");
System.exit(1);
}
}
System.out.println(total);
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Main {
public static void main(String[] argv) {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("c:\\a.txt")));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line + "\n");
line = br.readLine();
}
br.close();
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}