IO 输入输出 流 基本概念整理(FileInputStream,FileOutputStream)

来源:互联网 发布:淘宝店铺有访客没订单 编辑:程序博客网 时间:2024/06/04 19:46

IO 输入输出 流(FileInputStream,FileOutputStream

数据的通信管道

1、沿着一定的方向

2、沿着一定的路径

IO流

1、方向


输入流(读)input   特点: 有文件则读,无文件则报异常!

从外部(文件系统)  流入到  程序中 (jvm


输出流(写)output  特点: 有文件则覆盖,无文件则创建文件!(PS:可以追加,fos的第二个参数写成true即可追加写入)

从程序中  流入到  外部(文件系统)


2、类型

字节流byte  stream

处理二进制数据


字符流char reader/writer

处理字符数据


FileInputStream


3、功能

节点流

文件的简单的读写操作

包装流

有一些其他方法。这些方法能够使得程序员更加方便的

操作数据

桥梁流

基本上所有的流都遵循这样的规则:

1、将流的名字分为三部分

partA  功能/特点

partB  方向

partC  类型


对象的字符输出流

ObjectWriter

ObjectOutputStream


2、流 一般都是成对出现的

FileInputStream  FileOutputStream

FileReader  FileWriter

BufferedInputStreamReader

BufferedOutputStreamWriter

StringReader  StringWriter

System.in System.out


流:

占用资源

释放资源:  关闭


模板

FileInputStream fis = null;

try{


fis = new FileInputStream(f);

fis.read();

}

catch(Exception e)

{


}

finally{

fis.close();

}

public void someMethod()

{

FileInputStream fis = new FileInputStream(f);


fis.read();

......


fis.close();

}

public void otherMehtod()

{

try{

someMethod();

}catch(Exception e)

{


//asdasd

}


//do other things......


}

对于字节输入流:

avaliable

int i = read()

i 读取到的数据

int i = read(byte[] b)

b 读取到的数据

i 读取的长度


判断是否读到文件末尾?

i == -1


对于字节输出流

write(byte i)

write(byte[] b)

write(byte[] b ,int startIndex,int offset)



文件读取基本范例代码,这里是一个字节一个字节的读取!:


    public static void main(String[] args)

    {

        

        FileInputStream fis = null;

        try

        {

            //要处理FileNotFoundException

            // 相对路径 : 相对的是: 执行java命令所在的路径

            //  eclipse 执行java命令  默认是在:coreJava

            fis = new FileInputStream(new File("src/com/itany/coreJava/day17/a.txt"));

            //要处理  IOException

            int b = 0;

            while((b = fis.read()) != -1)

            {

               // System.out.println(b);

            }

            System.out.println("end");

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }finally{

            

            if(fis != null)

            {

                try

                {

                    fis.close();

                }

                catch (IOException e)

                {

                    e.printStackTrace();

                }

            }

            

        }

    }



1 0