Io流的FileInputStream和FileOutputStream的读取和写入

来源:互联网 发布:天刀血玲珑捏脸数据导 编辑:程序博客网 时间:2024/06/07 17:15

一 、如何读写文件

通过流来读取文件。流是指一连串流动的字符,是以先进先出的方式发送信息通道。

二、Java流的分类

按流的流向来分

1、输出流 Outputstream 和writer作为基类

2、输入流Inputstream和reader作为基类

输入和输出是相对于电脑内存来说的

按照处理数据单元划分

1、字节流

⑴字节输入流,inputstream基类;

⑵字节输出流,Outputstream基类;

2、字符流

⑴字符输入流Reader基类

⑵字符输出流Writer基类

注:1字符=2字节

字节是8位通用字节流,字符流是16位unicode字符流.

三、字节流与字符流的使用情况

1字符流:适用于文本文档的读取

2字节流:图片,音频,视频。确保失真度降到最低。

四、使用FileInputStream类读文本文件

实现步骤


eg:

1、import一些包。

2、FileInputStream fi=new FileInputStream("c\\test.txt")

3、fi.available();

   fi.read();

4、fi.close();

五、使用FileOutputStream类读文本文件

eg:

1、import一些包

2、FileOutputStream  fos=new FileOutStream("c\\test.test");

   String str="123456";

   byte[] s=str.getByte();

   fos.write(s);

3、fos.close();

六、常用的方法

⒈InPutStream和其子类FileInputStream常用的方法

⑴、类名.read();用int类型接收

从此输入流中读取一个数据字节。

⑵、类名.read(byte[] b);用int类型接收

从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。

⑶、类名.read(byte[]b,int off,int len);用int类型接收

   从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。

⑷、类名.close();

   关闭此文件输入流并释放与此流有关的所有系统资源。

⑸、类名.available();用int类型接收

 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数

子类FileInputStream常用的构造方法

⑴、FileInputStream(File file);

⑵、FileInputStream(String name);

 2、OutputStream和其子类FileOutputStream的常用方法

  ⑴、类名.write(int c);

     将指定字节写入此文件输出流。

  ⑵、类名.write(btye[]b);

     将 b.length 个字节从指定 byte 数组写入此文件输出流中。

  ⑶、类名.write(byte[] b, int off, int len);

 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入       此文件输出流。

子类FileOutputStream常用的构造方法

FileOutputStream(File file);

FileOutputStream(String name);

FileOutputStream(String name,boolean append);

注:前两种构造方法向文件写数据时候将覆盖文件中原有的内容

    创建FileOutputStream实例时候,如果相应的文件并不存在,将会自动创建新的空的文件。

例题:将E盘的文本文档的内容复制到c盘中

public static  void main(String[]args){

        try {

            FileInputStream   in=new FileInputStream("E:\\ee\\title.txt");

            FileOutputStream  out=new FileOutputStream("C:\\复制.txt");

            

            byte[]b=new byte[12];

            int len=0;

            while((len=in.read(b))!=-1){

                out.write(b, 0, len);

            }

            

            in.close();

            out.close();

        } catch (Exception e) {

            

            e.printStackTrace();

        }


   



阅读全文
0 0