IO流入门-第一章-FileInputStream

FileInputStreamj基本用法和方法示例

import java.io.*;

public class FileInputStreamTest01
{
    public static void main(String[] args){
        FileInputStream fis = null;
        try{
            //temp01的内容是:abcdefg
            String filePath = "temp01";    //相对路径
            //String filePath = "I:\java-study\io\temp01";    //绝对路径
            //String filePath = "I:/java-study/io/temp01";
            fis = new FileInputStream(filePath);

            //******************read()读取存在缺点:频繁访问磁盘,伤害磁盘,效率低。
            //开始读,读到末尾返回-1
            /*int i1 = fis.read();    //以字节的方式读取
            System.out.println(i1);
            */
    
            //循环读取
            /*while(true){
                int temp = fis.read();
                if(temp == -1) break;
                System.out.println(temp);
            }*/

            //升级循环读取
            /*
            int temp = 0;
            while((temp =fis.read()) != -1){
                System.out.println(temp);
            }
            */

            //******************read(byte[] bytes)
            //读取之前在内存中准备一个byte数组,每次读取多个字节存储到byte数组中,不是单字节读取了
            //byte数组相当于内存中的缓存,效率高

            //准备一个字节数组
            /*byte[] bytes = new byte[3];    //每次最多读取3个字节
            int i1 = fis.read(bytes);        //返回值代表的是读取了多少个字节。
            //将数组转换成字符串
            System.out.println(new String(bytes));
            //将数组的有效部分转换成字符串
            //System.out.println(new String(bytes,0,i1));
            */

            //循环读取
            /*byte[] bytes = new byte[1024];    //每次读取1KB
            while(true){
                int temp = fis.read(bytes);
                if(temp == -1) break;
                System.out.print(new String(bytes,0,temp));
            }
            */

            //升级循环读取
            /*int temp =0;        
            byte[] bytes = new byte[1024];
            while((temp = fis.read(bytes)) != -1){
                System.out.print(new String(bytes,0,temp));
            }
            */

            //available() 
            System.out.println(fis.available());    //返回流中估计剩余字节数

            //skip(),跳过并丢弃 n 个字节的数据
            fis.skip(2);
            System.out.println(fis.read());

        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e1){
            e1.printStackTrace();
        }finally{
            //流释放
            if(fis != null){
                try{
                    fis.close();                
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/bookwed/p/6704114.html