IO流分类
按流的方向分为:输入流 和 输出流
按数据结构分为:字节流 和 字符流
按角色分为:节点流 和 缓冲流(处理流
InputStream:字节输入流
OutputStream:字节输出流
Reader:字符输入流
Writer:字符输出流
IO体系
|抽象类|基本实现类(节点流)|缓冲流| |:—|:—|:—| |InputStream|FileInputStream|BufferedInputStream| |OutputStream|FileOutputStream|BufferedOutputStream (flush())| |Reader|FileReader|BufferedReader (readLine())| |Writer|FileWriter|BufferedWriter (flush())|
FileInputStream
public class TestFile {
public static void main(String[] args) {
// 声明文件
File f1 = new File("Test1.txt");
// 创建操作文件对象
FileInputStream fis = null;
try {
fis = new FileInputStream(f1);
byte[] bs = new byte[6];
while(fis.read(bs)!=-1 ) {
String s = new String(bs);
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fis !=null) {
try {
fis.close();
} catch (IOException e{
e.printStackTrace();
}
}
}
}
}
##FileOutputStream
public class TestFile2 {
public static void main(String[] args){
// 输出流的时候如果底层没有文件,系统会给你创建一个文件
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("Test2.txt"));
fos.write(new String("你在干嘛呢").getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos !=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
##利用缓冲流实现文件内容的拷贝
@Test
public void fun9() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(new File("Test1.txt")));
bw = new BufferedWriter(new FileWriter(new File("Test2.txt")));
String str;
while((str=br.readLine())!=null) {
bw.write(str);
}
bw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bw!=null)
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
if(br!=null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#