黑马程序员——java基础---IO流

来源:互联网 发布:下载picsart软件手机软件 编辑:程序博客网 时间:2024/06/06 01:39

IO流

IO,即input和output的首字母相连,input是输入,output是输出,所以io就是输入输出。io流是两端点间不可逆的数据传送,比如个人电脑和站点之间互相传送数据。

在java中io流分字节流和字符流,字节流以字节为读写单位,字符流以字符为读写单位。字节流和字符流都分别有对应文件和控制台上输入输出使用的类。

字节流

字节流分两大类,字节输入流InputStream和字节输出流OutputStream。
文件输入输出使用的字节流:FileInputStream
FileOutputStream

在io中,关于io流的类和接口存放在java.util.io包中。关于io方法的异常是IOException.

代码如下:

import java.io.*;class FileStream{    public static void main(String[] args)throws Exception    {        FileOutputStream fos = new FileOutputStream("fos.txt");        fos.write("hello,world".getBytes());        fos.close();        FileInputStream fis = new FileInputStream("fos.txt");        //available()方法可以获得文件的字节数        byte[] buf = new byte[fis.available()];        int len = 0;        while((len = fis.read(buf)) != -1)        {            System.out.print(new String(buf,0,len));        }        fis.close();    }}

字符流

字符流分两大类,字符输入流Reader和字符输出流Writer。
FileReader
FileWriter

class FWriter{    private FileWriter fw;    FWriter(String filename, String filetype)    {        /*         * 在         */        try        {            fw = new FileWriter(filename + "." + filetype,);        } catch (IOException e)        {            System.out.println("can not create a file.");        }    }    FWriter(String filename, String filetype, boolean b)    {    try    {        fw = new FileWriter(filename + "." + filetype,b);    } catch (IOException e)        {            System.out.println("can not create a file.");        }    }    //写入    public void writeIn(String s)    {        try        {            fw.write(s);            fw.flush();        } catch (IOException e)        {            System.out.println("can not write the file.");        }    }    //关闭文件    public void closeFile()    {        try        {            fw.close();        } catch (IOException e)        {            System.out.println("can not close the stream.");        }    }}
0 0
原创粉丝点击