码迷,mamicode.com
首页 > 编程语言 > 详细

java IO流(二)

时间:2015-12-10 13:21:20      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

   IO流主要用于硬板、内存、键盘等处理设备上得数据操作,根据处理数据的数据类型的不同可以分为:字节流(抽象基类为InputStream和OutputStream)和字符流(抽象基类为Reader和Writer)。根据流向不同,可以分为:输入流和输出流。一般探讨IO流时,是按数据类型来分的。

IO流的分类:

    流向:

      输入流  (读取数据)

      输出流  (写出数据)

    数据类型:

      字节流 

        字节输入流(读取数据) InputStream

        字节输出流 (写出数据)OutputStream

      字符流

        字符输入流 (读取数据) Reader

        字符输出流 (写出数据) Writer

 字符流和字节流的主要区别:

       1.字节流读取的时候,读到一个字节就返回一个字节;  字符流使用了字节流读到一个或多个字节(中文对应的字节数是两个,在UTF-8码表中是3个字节)时。先去查指定的编码表,将查到的字符返回。

       2.字节流可以处理所有类型数据,如:图片,MP3,AVI视频文件,而字符流只能处理字符数据。只要是处理纯文本数据,就要优先考虑使用字符流,除此之外都用字节流。

一、字节流:

  1、字节输出流:FileOutputStream

构造方法:

public FileOutputStream(File file)        

public FileOutputStream(String name)  

public FileOutputStream(String name,boolean append):当append设为true,可以在原有文件上追加数据

Write方法:

public void write(int b) :写一个字节到文件输出流

public void write(byte[] b) :从byte[]数组中写b.length个字节到文件输出流

public void write(byte[] b, int off, int len) :从索引为off开始,写len个长度的字节到文件输出流 

    void createFileOutputStream() throws IOException {
        FileOutputStream fos=new FileOutputStream("a.txt");

        fos.write("Hello World".getBytes());

        byte[] by={97,98,99,100};
        fos.write(by);

        byte[] by2={101,102,103,104,105};
        fos.write(by2,1,3);

        fos.close();
    }

最后给出加入了异常处理的字节输出流的写法:

  FileOutputStream fos= null;
        try {
            fos = new FileOutputStream("a.txt");
            fos.write("Hello World".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

 

java IO流(二)

标签:

原文地址:http://www.cnblogs.com/liujufu/p/5035488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!