IO流 :InputOutput流
流,是建立在CPU(当前CPU上执行的代码)和除了CPU以及内存以外的其他设备之间的信息通道
流的分类方式
根据传输的内容格式不同分为:字节和字符
根据传输的方向不同分为:输入流和输出流
根据传输过程不同分为:阻塞流和非阻塞流
根据前两个分配发式,进行一次笛卡尔积,得到4种不同的分法
输入字节流 | 输入字符流 |
---|---|
输出字节流 | 输出字符流 |
字节流输入输出
//输入字节流
try {
InputStream is = new FileInputStream("E:/aaa.txt");
byte[] b = new byte[1024];
while(is.read(b) >= 0) {
String str = new String(b,"UTF8");
System.out.println(str);
Arrays.fill(b, (byte)0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//输出字节流
try {
InputStream is = new FileInputStream("E:/aaa.txt");
OutputStream os= new FileOutputStream("E:/bbb.txt");
byte[] b = new byte[1024];
while(is.read(b) >= 0) {
os.write(b);
String str = new String(b,"UTF8");
System.out.println(str);
Arrays.fill(b, (byte)0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//字节流
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream("E:/aaa.txt");
os= new FileOutputStream("E:/bbb.txt",true);
byte[] b = new byte[1024];
while(is.read(b) >= 0) {
os.write(b);
String str = new String(b,"UTF8");
System.out.println(str);
Arrays.fill(b, (byte)0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
字符流输入输出
字符流不能传输二进制文件
//输入字符流
Reader reader;
try {
reader = new FileReader("E:/aaa.txt");
char[] cs = new char[1024];
while(reader.read(cs) >= 0) {
String str = new String(cs);
System.out.println(str);
Arrays.fill(cs, ' ');
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//输出字符流
Writer w;
try {
w = new FileWriter("E:/fw.txt");
w.write("sadasdasd");
w.flush();
} catch (IOException e) {
e.printStackTrace();
}
//字符流复制
Writer w1;
Reader r1;
try {
r1 = new FileReader("E:/aaa.txt");
w1 = new FileWriter("E:/fw.txt");
char[] buf = new char[512];
while(r1.read() >= 0) {
w1.write(buf);
Arrays.fill(buf, ' ');
}
w1.flush();
} catch (IOException e) {
e.printStackTrace();
}