zoukankan      html  css  js  c++  java
  • IO流

    一、字节流

    1一切皆为字节

    一切文件数据(文本、图片、视频等)在储存时都是以二进制数字的形式保存的,都是一个个的字节,传输时也是如此,无论使用什么样的流对象,底层传输始终为二进制数据。

    2字节输出流

    java.io.OutputStream 抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。 
    public void close() :关闭此输出流并释放与此流相关联的任何系统资源。 
    public void flush() :刷新此输出流并强制任何缓冲的输出字节被写出。 
    public void write(byte[] b) :将 b.length字节从指定的字节数组写入此输出流。 
    public void write(byte[] b, int off, int len) :从指定的字节数组写入 len字节,从偏移量off开始输出到此输出流。 
    public abstract void write(int b) :将指定的字节输出流。 
    小贴士: 
    close方法,当完成流的操作时,必须调用此方法,释放系统资源。

    3.FileOutputStream类

    FileOutputStream类是OutputStream类的一个子类,文件输出流,用于将数据写出到文件。

    public FileOutputStream(File file) :创建文件输出流以写入由指定的 File对象表示的文件。 
    public FileOutputStream(String name) : 创建文件输出流以指定的名称写入文件。
    当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据。 
    构造举例,代码如下: 
    public class FileOutputStreamConstructor throws IOException { 
    public static void main(String[] args) { 
    // 使用File对象创建流对象 
    File file = new File("a.txt"); 
    FileOutputStream fos = new FileOutputStream(file); 
    // 使用文件名称创建流对象 
    FileOutputStream fos = new FileOutputStream("b.txt"); 
    } 
    } 
    写出字节: write(int b) 方法,每次可以写出一个字节数据,代码使用演示: 
    public class FOSWrite {
    public static void main(String[] args) throws IOException { 
    // 使用文件名称创建流对象 
    FileOutputStream fos = new FileOutputStream("fos.txt"); 
    // 写出数据 
    fos.write(97); // 写出第1个字节 
    fos.write(98); // 写出第2个字节 
    fos.write(99); // 写出第3个字节 
    // 关闭资源 
    fos.close(); 
    } 
    } 
    输出结果: 
    abc 
    小贴士: 
    1. 虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。 
    2. 流操作完毕后,必须释放系统资源,调用close方法,千万记得。 
    写出字节数组: write(byte[] b) ,每次可以写出数组中的数据,代码使用演示: 
    public class FOSWrite { 
    public static void main(String[] args) throws IOException { 
    // 使用文件名称创建流对象 
    FileOutputStream fos = new FileOutputStream("fos.txt"); 
    // 字符串转换为字节数组 
    byte[] b = "同志们好".getBytes(); 
    // 写出字节数组数据 
    fos.write(b); 
    // 关闭资源 
    fos.close(); 
    } 
    } 
    输出结果: 
    同志们好
    写出指定长度字节数组: write(byte[] b, int off, int len) ,每次写出从off索引开始,len个字节,代码 
    使用演示: 
    public class FOSWrite { 
    public static void main(String[] args) throws IOException { 
    // 使用文件名称创建流对象 
    FileOutputStream fos = new FileOutputStream("fos.txt"); 
    // 字符串转换为字节数组 
    byte[] b = "abcde".getBytes(); 
    // 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。 
    fos.write(b,2,2); 
    // 关闭资源 
    fos.close(); 
    } 
    } 
    输出结果: 
    cd
  • 相关阅读:
    Codeforces Round #380(div 2)
    Codeforces Round #378(div 2)
    Codeforces Round #379(div 2)
    CCPC2016合肥现场赛
    CCPC2016沈阳站
    HDU2222 Keywords Search__AC自动机
    poj2185Milking Grid
    POJ2961_kmp
    POJ 2406
    poj 2752Seek the Name, Seek the Fame
  • 原文地址:https://www.cnblogs.com/hsRick/p/11452453.html
Copyright © 2011-2022 走看看