IO流的基本使用方法

来源:互联网 发布:2016年双11淘宝交易额 编辑:程序博客网 时间:2024/05/16 08:04

IO流主要用来做数据的传输,比如输入输出等操作,分为字节流和字符流。字符流主要处理一个文本文件的传输,字节流则什么类型的文件都可以。以下分类介绍这些流的使用方法:

  • 字节流
    字节流有两个基本的抽象(abstract)类:InputStream(输入流超类),OutputStream(输出流超类)
    普通字节流的文件操作:
//基本字节流,一次读取一个字节(效率很低)static void copy(String src, String dest) throws IOException{    FileInputStream  inputStream = new FileInputStream(src);    FileOutputStream outputStream = new FileOutputStream(dest);    //每次读取数据到by,当等于-1时文件读取完成    int by = 0;    while((by = inputStream.read())!= -1){        outputStream.write(by);    }    outputStream.close();    inputStream.close();}
//基本字节流,一次读取一个字节数组static void copy(String src, String dest) throws IOException {    FileInputStream inputStream = new FileInputStream(src);    FileOutputStream outputStream = new FileOutputStream(dest);    //每次读取数据到bys字节数组,当等于-1时文件读取完成    byte[] bys = new byte[1024];    int length = 0;    while ((length = inputStream.read(bys)) != -1) {        outputStream.write(bys, 0, length);    }    outputStream.close();    inputStream.close();}
0 0