IO流的总结
1. IO的流向说明图
2. 字节流
2.1 一切文件皆字节
一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都是一个一个字节,那么在传输时也是一样。所以,字节流可以是传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终是二进制的数据。
2.2 字节输出流【OutputStream】
FileOutputStrem
常用:
write(int b)方法
FileOutputStream fs = new FileOutputStream("gg.txt");
fs.write(97);
fs.close();
注意:在调构造方法的时候就创建了文件,并不是write时才创建
write(byte[] b)方法
注意:一次写多个字节,如果写的第一个字节是正数(0~127间),那么显示的时候会查询ASCII表;如果写的第一个字节是负数,那么第一个会和第二个字节组成一个中文显示,查询系统的默认码表(GKB);
FileOutputStream fs = new FileOutputStream("gg2.txt");
byte [] bytes = {65,66,-67,68,69};
fs.write(bytes);
fs.close();
write(byte[] b,int off,int len)方法
将字节数组的一部分写入文件中
FileOutputStream fs = new FileOutputStream("gg2.txt");
byte[] bytes ="信息2".getBytes();
fs.write(bytes,0,bytes.length);
fs.close()
追加写/续写(不覆盖)
FileOutputStream fs = new FileOutputStream("gg2.txt",true);
byte[] bytes ="呵呵".getBytes();
for(int i=0;i<5;i++){
fs.write(bytes,0,bytes.length);
fs.write("\r\n".getBytes());
}
fs.close();
2.3 字节输人流【InputStream】
FileOutputStrem
复制文件例子:
package com.chw.io;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class FileInputStreamTest {
public static void main(String[] args) throws Exception {
test01();
}
private static void test01() throws Exception {
FileInputStream fis = new FileInputStream("gg2.txt");
FileOutputStream fos = new FileOutputStream("gg3.txt");
//ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len;
while((len=fis.read(buff))!=-1){
fos.write(buff, 0,len);
//baos.write(buff, 0, len);
}
fis.close();
fos.close();
}
}
3. 字符输入流 【Reader】
FileReader
package com.chw.io;
import java.io.FileReader;
public class ReaderTest {
public static void main(String[] args) throws Exception {
test01();
}
private static void test01() throws Exception {
FileReader fr = new FileReader("gg3.txt");
// int len;
// while((len=fr.read())!=-1){
// System.out.print(new StringBuffer(len));
// }
char [] cs = new char[1024];
int len;
while((len=fr.read(cs))!=-1){
System.out.println(new String(cs));
}
fr.close();
}
}