您的位置:首页 > 职场人生

黑马程序员——JAVA基础——IO流

2015-08-17 13:55 501 查看
----------android培训、java培训、java学习型技术博客、期待与您交流!------------ 
一、
一、IO流的三种分类方式

    1.按流的方向分为:输入流和输出流

    2.按流的数据单位不同分为:字节流和字符流

    3.按流的功能不同分为:节点流和处理流

    二、IO流的四大抽象类:

    字符流:Reader Writer

    字节流:InputStream(读数据)

    OutputStream(写数据)

    三、InputStream的基本方法

    int read() throws IOException 读取一个字节以整数形式返回,如果返回-1已到输入流的末尾

    void close() throws IOException 关闭流释放内存资源

    long skip(long n) throws IOException 跳过n个字节不读

    四、OutputStream的基本方法

    void write(int b) throws IOException 向输出流写入一个字节数据

    void flush() throws IOException 将输出流中缓冲的数据全部写出到目的地

    五、Writer的基本方法

    void write(int c) throws IOException 向输出流写入一个字符数据

    void write(String str) throws IOException将一个字符串中的字符写入到输出流

    void write(String str,int offset,int length)

    将一个字符串从offset开始的length个字符写入到输出流

    void flush() throws IOException

    将输出流中缓冲的数据全部写出到目的地

    六、Reader的基本方法

代码详解:

System.in

    int read() throws IOException 读取一个字符以整数形式返回,如果返回-1已到输入流的末尾

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

/*

 * System.in是InputStream static final的,包含了多态,叫同步式或者阻塞式

 * 读取ASCII和二进制文件(图片),而字母就是ASCII字符(个人理解)。

 */

public class TestSystemIn {

 public static void main(String[] args) {

  InputStreamReader isr = new InputStreamReader(System.in);

  BufferedReader br = new BufferedReader(isr);//有readline

  String s = null;

  try {

   s = br.readLine();

   while(s!=null) {

    if(s.equalsIgnoreCase("exit")) {

     break;

    }

    System.out.println(s.toUpperCase());

    s = br.readLine();

   }

   br.close();

  }catch (IOException e) {

   e.printStackTrace();

  }

 }

}

八,FileInputStream

import java.io.*;

public class TestFileInputStream {

 public static void main(String[] args) {

  FileInputStream in = null;

  try {

   in = new FileInputStream("e:/1.txt");

  }catch(FileNotFoundException e) {

   System.out.println("找不到文件");

   System.exit(-1);

  }

  //下面表示找到了文件

  int tag = 0;

  try {

   long num = 0;

   while((tag = in.read())!=-1) {

    //read是字节流,若是有汉字就显示不正常了,使用reader就解决了

    System.out.print((char)tag);

    num++;

   }

   in.close();

   System.out.println();

   System.out.println("共读取了" + num + "字符");

  }catch(IOException e1) {//read和close都会抛出IOException

   System.out.println("文件读取错误");

   System.exit(-1);

  }

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: