首页 > 解决方案 > java 除了EOF之外,有没有办法像C ++一样结束

问题描述

EOF是为C++本身定义的 但是如果JAVA中没有EOF呢?示例图片

标签: java

解决方案


JavaInputStream#read将完全如此,返回 -1 (C/C++) EOF 或字节范围内的其他 int,无符号为 0 .. 255。

但是,Java 中的String(带有Readerand Writer)是针对 Unicode 文本的,char它是一个 2 字节的 UTF16 值。Input-and用于二进制数据,需要一些编码 ( OutputStream)将其转换为.byteCharsetString

    byte[] read(InputStream in) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int c;
        while ((c = in.read()) != -1) {
            baos.write((byte) c); // Cast not needed, as int.
        }
        return baos.toByteArray();
    }

    String read(InputStream in) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int c;
        while ((c = in.read()) != -1) {
            baos.write((byte) c); // Cast not needed, as int.
        }
        return baos.toString("UTF-8"); // Conversion provided.
    }

推荐阅读