【Java梳理】IO流

2017-12-12  本文已影响0人  田文健

IO即输入输出的缩写。在程序中输入输出数据是很常见的操作。在Java中经常使用的方式是流(Stream)。流是操作输入输出设备的一种抽象,它可以操作很多种存在不同文件类型,以及网络传输的数据。InputStream对应从程序外部读入数据,OutputStream对应程序写数据到外部。

如文件流FileInputStream/FileOutputStream。下面是一个以字节方式读写文件的例子,

public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("example.txt");  //此文件在项目的根目录下

            byte[] bytes = new byte[fileInputStream.available()];  //获取可读的字节,并创建存放它的数组

            fileInputStream.read(bytes, 0, bytes.length);  //把可读的字节全部读入

            System.out.println(new String(bytes));  //转换为字符串输出, 乱码时需指定编码哦

            //FileOutputStream fileOutputStream = new FileOutputStream("");

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

在使用流之后,不要忘了close它。也可以使用try with resource 自动关闭,这在之前的异常章节有介绍。

还有其他的适合处理各种情况的IOStream,如:
DataInputStream: 可以按类型读出数
ObjectInputStream ; 读出一个对象,在序列化中常用
....

上一篇 下一篇

猜你喜欢

热点阅读