文章目录
为了提高文章的可阅读性,在本文的示例程序中,对于异常的处理采取了直接抛出,减少了try/catch,使得代码简凑易读。请读者在实操时用try/catch代码块进行处理!
字节流
FileInputStream & FileOutputStream
下面介绍这两个类的使用
新建一个文件"C_01.txt",写入Morning!
,共8个字节
FileInputStream
FileInputStream对象在创建时与文件建立了连接,用于从文件中读取原始字节流,因此不适合读取含有非单字节编码的符号(如中文)的文件。
1.流对象与文件建立连接
FileInputStream in = new FileInputStream(new File("C_01.txt"));
2.返回剩余可以被读取(或跳过)的字节数
System.out.println(in.available()); //8
3.判断流对象是否支持mark和reset
System.out.println(in.markSupported()); //false
4.读取并返回下一个字节
int read = in.read();
System.out.println((char)(read)); //M
- 读取字节流存入bytes数组 最多读入bytes.length大小的内容,返回读取的字节数
byte[] bytes = new byte[10];
System.out.println(in.read(bytes)); //8
System.out.println(new String(bytes));//Morning!
6.读取指定长度的字节,从字节数组的的指定偏移量开始存放,,返回读取的字节数
int read(byte[] b,int off,int len)
byte[] bytes = new byte[20];
System.out.println(in.read(bytes,10,3)); //3
System.out.println((char)bytes[10]); //M
System.out.println((char)bytes[12]); //r
7.返回剩余的字节组成的字节数组
byte[] bytes = in.readAllBytes();
System.out.println(new String(bytes)); //Morning!
8.读取指定长度的字节,从字节数组的指定偏移量开始存放,返回读取的字节数
byte[] bytes = new byte[20];
int len = in.readNBytes(bytes,0,2);
System.out.println(len); //2
System.out.println(new String(bytes)); //Mo
9.读取指定长度的字节,返回一个字节数组
byte[] bytes = in.readNBytes(7);
System.out.println(bytes.length); //7
System.out.println(new String(bytes)); //Morning
10.跳过n个字节
in.skip(7);
System