首页 > 编程语言 > 详细

Java的输入与输出流InputStream/OutputStream

时间:2020-03-04 21:02:00      阅读:71      评论:0      收藏:0      [点我收藏+]

先看InputStream和FileInputStream的结构

技术分享图片

操作输入流的步骤:

  1. 创建源
  2. 选择流
  3. 操作
  4. 释放源

 

代码示例:

import org.testng.annotations.Test;
import java.io.*;

public class FileDemo {

    @Test
    public void fileTest() {

        //1.创建源
        File file = new File("jerry.txt");

        //2.选择流
        InputStream in = null;

        //3.操作
        try {
            in = new FileInputStream(file);
            int temp;
            while (true) {

                if (!((temp = in.read()) != -1)) break;
                //read()返回是字符的编码,我们要读取的字符是英文,所以转义成char
                System.out.print((char) temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
            //4.关闭流
            //注意:close()要卸载finally里面。
            //如果不写在finally里面,而是写在前面catch里面,当出现异常时,close就不会被执行
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

Java的输入与输出流InputStream/OutputStream

原文:https://www.cnblogs.com/majestyking/p/12416051.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!