InputStream vs Reader
InputStream
|
|__ FileInputStream
FileInputStream (File file)
Reader
|
|—— BufferedReader
|
|__ InputStreamReader
|
|__ FileReader
BufferedReader (Reader in, [int size])
InputStreamReader (InputStream in, [Charset cs])
FileReader (File file)
InputStream
read file inbytes
,Reader
read file inchars
InputStreamReader vs FileReader
InputStreamReader
can handleall input streams
, not just files. Other examples arenetwork connections
,classpath resources
andZIP
files
InputStreamReader
could specificCharSet
encoding
Why use Buffered IO
For
unbuffered I/O stream
,each read or write
request is handleddirectly
by theunderlying OS
. This can make a program muchless efficient
, since each such request oftentriggers disk access
, network activity, or some other operation that is relatively expensive.
Example to use InputStreamReader or FileReader
InputStreamReader
try {
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr);
} catch(Exception e) {
e.printStackTrace();
}
FileReader
try {
File file = new File("test.txt");
FileReader fr = new FileReader(file);
BufferedReader reader = new BufferedReader(fr);
} catch(Exception e) {
e.printStackTrace();
}
Write into file using Buffered IO
try {
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr);
File file2 = new File("test2.txt");
FileOutputStream fos = new FileOutputStream(file2);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter writer = new BufferedWriter(osw);
String s;
while((s = reader.readLine()) != null){
writer.write(s, 0, s.length());
writer.newLine();
// do not forget
writer.flush();
}
isr.close();
osw.close();
}
catch(IOException e) {
System.out.println(e);
}