分类:按数据流分输入流(读入数据)和输出流(写入数据),按照数据类型分字节流和字符流。
- 字节流:抽象基类 InputStream、OutputStream,子类:FileInputStream、FileOutputStream、BufferedInputStream、BufferedOutputStream等多个子类,其中后两者为高效流
- 字符流:抽象基类 Reader、Writer,子类:InputStreamReader、OutputStreamWriter、FileReader、FileWriter、BufferedReader、BufferedWriter等多个,其中InputStreamReader和OutputStreamWriter为转换流,InputStreamReader(InputStream is) 可以将字节流转换成字符流,后两者为高效流。
使用字符流时,可以指定编码 InputStreamReader(InputStream is,StringcharSetName)。
flush()和close()区别:flush()刷新缓冲区,流对象还可以继续使用,close()先刷新缓冲区,关闭流对象,流对象不可以使用
具体使用如下:
- 基本字节流,一次读写一个字节
- 基本字节流,一次读写一个字节数组
- 高效字节流,一次读写一个字节
- 高效字节流,一次读写一个字节数组
- 字符流,一次读写一个字符
- 字符流,一次读写一个字符数组
- 高效字符流,一次读写一行
基本字节流,一次读写一个字节
private static void method1(String src, String dest) throws Exception {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
int by;
while ((by = fis.read()) != -1) {
fos.write(by);
}
fis.close();
fos.close();
}
基本字节流,一次读写一个字节数组
private static void method2(String src, String dest) throws Exception {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
byte[] bytes = new byte[1024 * 8];
int len;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
fis.close();
fos.close();
}
高效字节流,一次读写一个字节
private static void method3(String src, String dest) throws Exception {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest));
int by;
while ((by = bis.read()) != -1) {
bos.write(by);
}
bis.close();
bos.close();
}
高效字节流,一次读写一个字节数组
private static void method4(String src, String dest) throws Exception {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest));
byte[] bytes = new byte[1024 * 8];
int len;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bis.close();
bos.close();
}
字符流,一次读写一个字符
private static void method5(String src, String dest) throws Exception{
InputStreamReader isr = new InputStreamReader(new FileInputStream(src));
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(dest));
int ch;
while((ch = isr.read()) !=-1){
osw.write(ch);
}
isr.close();
osw.close();
}
字符流,一次读写一个字符数组
private static void method6(String src, String dest) throws Exception{
InputStreamReader isr = new InputStreamReader(new FileInputStream(src));
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(dest));
char[] chs = new char[8*1024];
int len;
while((len = isr.read(chs)) !=-1){
osw.write(chs,0,len);
}
isr.close();
osw.close();
}
高效字符流,一次读写一行
private static void method7(String src, String dest) throws Exception{
BufferedReader br = new BufferedReader(new FileReader(src));
BufferedWriter bw = new BufferedWriter(new FileWriter(dest));
String line;
while((line = br.readLine()) != null){
bw.write(line);
}
br.close();
bw.close();
}