IO流(字节输入流)
步骤:
创建输入流对象
读数据:通过读取文件,显示在控制台
释放资源
读取数据:
1.public int read():一次读取一个字节
核心部分:
int by = 0;
while( (by = fis.read()) != -1){
System.out.println((char)by);
}
代码:
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("e:\\c.txt");
//一次读取一个字节
int by = 0;
while((by= fis.read()) !=-1){
System.out.print((char)by);
}
System.out.println();
fis.close();
}
结果:
Hello
Java
I Love You !
2.public int read(byte[] b):一次读取一个字节数组
3.public int read(byte[] b , int off , int len ):从此输入流中将最多len个字节数据读入byte数组中
核心部分:
byte[] bys = new byte[1024];
int len = 0;
while( ( len = fis.read (bys) ) !=-1){
System.out.println(new String (bys, 0, len ));
}
代码:
public static void main(String[] args) throws IOException {
FileInputStream fis2 = new FileInputStream("e:\\c.txt");
byte[] bys2 = new byte[1024];
int len ;
while((len = fis2.read(bys2))!= -1){ 直接将读到的字节数存储到字节数组中
String s = new String (bys2,0,len);
System.out.print(s);
//System.out.println(new String(bys2,0,len);
}
System.out.println();
fis2.close();
}
结果:
Hello
Java
I Love You !