/*
* IO流: 作用:用于设备和设备之间的数据传输 * File类的使用:操作文件的属性 * * IO流 用来操作文件的数据 * * 分类: * 流按照操作数据的类型分为:字节流 / 字符流 * * 字节流:读取的是文件的二进制数据,不会对二进制做处理.不会解析成比看得懂的数据 * 字符流:读取的是二进制数据。他会将二进制数据转化为我们能过别的字符(解码)。字符流是以字符为单位 *字符流 = 字节流 +解码 * 流按照流的方向: 输入流和输出流 * 判断流是输出还是输入以当前的应用程序为参考,观察数据是流入还是流出,如果是流出就是输出流 * * 先来看字节输入流 * InputStream 此抽象类是表示字节输入流的所有类的超类,抽象类 * * 如何判断一个流值字节输入流 * 判断他的类名是否以InputStream结尾 * 使用FileInputStream 是InputStream的子类 * 使用步骤 * 1.找到目标文件
package IO02;
import java.io.File;
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class Demo3 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub getFile(); getFile2(); getFile3(); getFile4(); } //方法四 public static void getFile4() throws IOException{ File file = new File("C:\\JAVA学习/a.txt"); //2.建立通道FileInputStream fileInputStream = new FileInputStream(file); //3.建立一个缓冲区 byte[] b = new byte[1024]; int count=0; while((count = fileInputStream.read(b))!=-1){ System.out.print("方法四:"+new String(b,0,count)); } //5.关闭资源 fileInputStream.close(); } //方法3 public static void getFile3() throws IOException{ File file = new File("C:\\JAVA学习/a.txt"); //2.建立通道 FileInputStream fileInputStream = new FileInputStream(file); //3.创建一个缓冲区 byte[] b = new byte[1024]; int count = fileInputStream.read(b); System.out.println(count); System.out.println("方法三:"+new String(b,0,count)); //5.关闭资源 fileInputStream.close(); } //方法二 //1.找到目标文件 public static void getFile2() throws IOException{ File file = new File("C:\\JAVA学习/a.txt"); //2.建立通道 FileInputStream fileInputStream = new FileInputStream(file); //3.读数据 /*for (int i = 0; i < file.leng(); i++) { char c = (char)fileInputStream.read(); System.out.println(c); } */ int content = 0; while ((content = fileInputStream.read())!=-1) { System.out.print("方法二:"+(char)content); } } public static void getFile() throws IOException{//方法一 //1.找到目标文件 File file = new File("C:\\JAVA学习/a.txt"); //2.建立通道 FileInputStream fileInputStream = new FileInputStream(file); //3.读取文件中的数据 //read()只获取一个字节 int data = fileInputStream.read(); System.out.println("获取数据 :" + data); //4.关闭资源 fileInputStream.close();} }