进阶day09-字节输入流的基本使用&一次读取一个字节
This commit is contained in:
68
javaSE-day09/src/com/inmind/inputstream02/Demo06.java
Normal file
68
javaSE-day09/src/com/inmind/inputstream02/Demo06.java
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
package com.inmind.inputstream02;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/*
|
||||||
|
在java中使用抽象类InputStream表示字节输入流
|
||||||
|
常用的子类:FileInputStream
|
||||||
|
FileInputStream的作用;将硬盘中的文件的数据读取到内存
|
||||||
|
构造方法:
|
||||||
|
FileInputStream(File file) 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
|
||||||
|
FileInputStream(String name) 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
|
||||||
|
常用方法:
|
||||||
|
void close() 关闭资源
|
||||||
|
int read() 从该输入流读取一个字节的数据。返回值就是字节数据
|
||||||
|
int read(byte[] b) 从字节输入流中将字节数据读取到参数b数组中,返回的值读取的字节个数
|
||||||
|
|
||||||
|
字节输入流的基本使用
|
||||||
|
步骤:
|
||||||
|
1.创建对象
|
||||||
|
2.调用读方法
|
||||||
|
3.释放资源
|
||||||
|
*/
|
||||||
|
public class Demo06 {
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
/*
|
||||||
|
1.创建对象
|
||||||
|
注意:
|
||||||
|
1.创建输入流对象时,文件不存在是报异常java.io.FileNotFoundException: b.txt
|
||||||
|
2.创建输出流对象是,文件不存在才会新建
|
||||||
|
*/
|
||||||
|
FileInputStream fis = new FileInputStream("a.txt");
|
||||||
|
|
||||||
|
//2.调用读方法
|
||||||
|
//int read() 从该输入流读取一个字节的数据。返回值就是字节数据
|
||||||
|
/*int c = fis.read();
|
||||||
|
System.out.println(c);//97
|
||||||
|
|
||||||
|
c = fis.read();
|
||||||
|
System.out.println(c);//98
|
||||||
|
|
||||||
|
c = fis.read();
|
||||||
|
System.out.println(c);//99
|
||||||
|
|
||||||
|
c = fis.read();
|
||||||
|
System.out.println(c);//-1*/
|
||||||
|
|
||||||
|
/*使用while循环来优化以上代码
|
||||||
|
返回值不是-1,则一直读取
|
||||||
|
*/
|
||||||
|
int c;//用来接收字节输入流读取的字节数据
|
||||||
|
/*
|
||||||
|
循环条件:(c = fis.read())!=-1
|
||||||
|
执行顺序:
|
||||||
|
1.fis.read():从字节输入流中读取一个字节数据
|
||||||
|
2.c = fis.read():将读取到的字节数据赋值给变量c
|
||||||
|
3.(c = fis.read())!=-1:判断是否读取到字节数据,如果读到那么继续操作
|
||||||
|
*/
|
||||||
|
while ((c = fis.read())!= -1) {
|
||||||
|
System.out.println((char) c);//按照ascii码表展示
|
||||||
|
}
|
||||||
|
|
||||||
|
//3.释放资源
|
||||||
|
fis.close();
|
||||||
|
System.out.println("程序结束");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user