IO流 : 做用 :用于设备和设备之间的数据传输。
File类的使用 :操做问价的属性
IO流:用来操做文件的数据。
IO流的分类:
流按照操做数据的类型分为两种: 字节流 ,字符流
字节流 : 读取的是文件的二进制数据,不会对二进制作处理。不会解析成比看得懂的数据。
字符流 :读取的也是二进制数据,他会将二进制数据转化为咱们能过识别的字符(解码)。 字符流是以字符单位的。
字符流 = 字节流 + 解码。
流按照流的方向: 输入流和输出流。
判断流是输出仍是输入: 以当期的应用程序为参考 ,观察数据是流入仍是流出,若是是流入就输入流 ,若是是流出就是输出流。
//====================字节流========================
1.字节输入流:
InputStream :此抽象类是表示字节输入流的全部类的超类 ,抽象的类
如何判断一个流值字节输入流 :
判断一下他的类名是否以InputStream结尾。
使用 FileInputStream: 是InputStream的子类
FileInputStream使用步骤:
1.找到目标文件
2.创建通道
3.建立一个缓冲区
4.读取数据
5.关闭资源
public class Demo1 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// getFile();
// getFile2();
// getFile3();
getFile4();
}
//方式四:经过建立缓冲区和循环的方式来读取
public static void getFile4() throws IOException{
//1.找目标文件
File file = new File("D:\\java课件及资料\\第十九次课\\代码\\Day19\\src\\com\\beiwo\\homework\\HomeWork.java");
//2.创建通道
FileInputStream fileInputStream = new FileInputStream(file);
//3.建立一个缓冲区
byte[] b = new byte[1024]; // 通常写1024倍数
//4.读取数据
int count = 0;
while((count = fileInputStream.read(b))!=-1){
System.out.println(new String(b,0,count));
}
//5.关闭资源
fileInputStream.close();
}
//方式三:建立缓冲区来读取数据 缺陷不可以读取一个完整的文件
public static void getFile3() throws IOException{
//1.找目标文件
File file = new File("D:\\a.txt");
//2.创建通道
FileInputStream fileInputStream = new FileInputStream(file);
//3.建立一个缓冲区
byte[] b = new byte[1024];
//4.读数据
//缓冲区来读数据 : 数据存在哪里
//数据是存在缓存区字节数组中的
//返回值就是文件的大小。
int count = fileInputStream.read(b);
System.out.println(count);
//String里面帮咱们作了解码功能
System.out.println(new String(b, 0, count));
//5.关闭资源
fileInputStream.close();
}
//方法二:用循环来读取字节数 缺点读取的效率不高
public static void getFile2() throws IOException{
//1.找目标文件
File file = new File("D:\\a.txt");
//2.创建通道
FileInputStream fileInputStream = new FileInputStream(file);
//3.读数据
/*for(int i = 0;i<file.length();i++ ){//有多少个字节就去多少次
char c = (char)fileInputStream.read();
System.out.print(c);
}*/
int c 0;
//经过while循环调用read()的方法 ,若是返回的值以-1表示文件没有内容了。
while((c fileInputStream.read())!= -1){
System.out.print((char)content);
}
//4.关闭资源
fileInputStream.close();
}
//方法一:每次只读取一个字节
public static void getFile() throws IOException{
//1.找到目标文件
File file = new File("D:\\a.txt");
//2.创建通道
FileInputStream fileInputStream = new FileInputStream(file);
//3.读取文件中的数据
//read() 只获取一个字节
int data = fileInputStream.read(); //a 第一个字节
int data2 = fileInputStream.read();
System.out.println("获取的数据:"+data2);
//4.关闭资源(释放资源)
fileInputStream.close();
}
}