zoukankan      html  css  js  c++  java
  • Java学习笔记之 IO包 字节流

    IO包最重要的五个类和一个接口

    File/OutputStream/InputStream(字节流)/Writer/Reader(字符流)

    一个接口:Serializable

     

    File类:



    字节流:

    OutputStreamInputStream是抽象类

    OutputStream是整个IO包中。字节输出流的最大类

    FileOutputStream是一个子类,通经常使用整个子类通过多态实例化OutputStream


     


     

     


    packageiotest;

     

    importjava.io.File;

    importjava.io.FileNotFoundException;

    importjava.io.IOException;

    importjava.io.OutputStream;

    importjava.io.FileOutputStream;

    importjava.io.InputStream;

    importjava.io.FileInputStream;

     

    publicclass OutputStreamDemo1 {

    public static void main(String args[]) throws Exception{

    File f =newFile("D:"+File.separator+"javasrc"+File.separator+"write_file.txt");

    OutputStream o=null;

    o=new FileOutputStream(f);

    String s="Hello World!";

    byte b[]=s.getBytes();

    o.write(b);

    o.close();

    //改动文件 追加文件内容

    OutputStream o1=null;

    o1=new FileOutputStream(f,true);

    o1.write(" ".getBytes()); //添加换行符

    o1.write(b);

    o1.close();

     

    //读取并打印文件

    //01 定义一个字节数组 长度为1024

    InputStream in1=null;

    in1=new FileInputStream(f);

    byte b1[]=new byte[1024];

    int len=in1.read(b1);

    in1.close();                

    print(b1,len);

     

    //02 定义一个字节数组 长度为文件长度

    InputStream in2=null;

    in2=new FileInputStream(f);

    byte b2[]=new byte[(int)f.length()];

    in2.read(b2);

    in2.close();

    print(b2);

     

           //03 已经文件长度 逐个字节读取

                  InputStream in3=null;

    in3=new FileInputStream(f);

    byte b3[]=new byte[(int)f.length()];

    for (int i=0;i<b3.length;i++){

    b3[i]=(byte) in3.read();

    }

    in3.close();

    print("the third read method:");

    print(b3);

         

    //04 未知文件长度读取

    InputStream in4=null;

    in4=new FileInputStream(f);

    byte b4[]=new byte[1024];

    int i=0;

    int temp=0;

    while ((temp=in4.read())!=-1){

    b4[i]=(byte)temp;

    i++;

    }

    in4.close();

    print("the fourth read method:");

    print(b4);

    }

     

    public static void print(byte b[],int len){

    System.out.println(new String(b,0,len));

    }

    public static void print(byte b[]){

    System.out.println(new String(b));

    }

    public static void print(String b){

    System.out.println(b);

    }

     

    }

  • 相关阅读:
    BZOJ4889: [TJOI2017]不勤劳的图书管理员
    BZOJ3932: [CQOI2015]任务查询系统
    BZOJ1926: [Sdoi2010]粟粟的书架
    POJ 3281 Dining(网络流-拆点)
    POJ 1273 Drainage Ditches(网络流-最大流)
    POJ 1325 Machine schedine (二分图-最小点覆盖数=最大匹配边数)
    HDU 1281 棋盘游戏
    HDU2255 奔小康赚小钱钱(二分图-最大带权匹配)
    HDU 2444 The Accomodation of Students (二分图存在的判定以及最大匹配数)
    POJ 3660 cow contest (Folyed 求传递闭包)
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/8487739.html
Copyright © 2011-2022 走看看