A类,使用其 实例化的子类
public class InputStreamDemo {
// 构造方法:为流对象绑定数据源
public static void main(String[] argStrings) {
/*内部方法 有返回值
* int read(int b)
* int read(byte[] b)
* int read(byte[] b,int start,int end)
*/
FileInputStreamDemo.func();
FileInputStreamDemo.func2();
}
static class FileInputStreamDemo{
public static void func() {
FileInputStream fileInputStream=null;
try {
fileInputStream = new FileInputStream("e:\\fileOut.txt");
// 重点:read()执行一次,自动读取下一个字节
// 返回值返回的是读取到的字节
// 到达文件结尾,返回-1
// 循环读取
int len=0;
while ((len=fileInputStream.read())!=-1) {
System.out.println(len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileInputStream!=null) {
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void func2() {
// 读取字节数组
FileInputStream fileInputStream=null;
try {
fileInputStream = new FileInputStream("e:\\fileOut.txt");
byte[] bytes=new byte[1024];
// 重点:返回有效字节数
int len=0;
while ((len=fileInputStream.read(bytes))!=-1) {
// 重点:使用String类构造重载 将字节数组转换字符串 同时设定转换的数组长度
String string=new String(bytes,0,len);
System.out.println(string);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileInputStream!=null) {
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}