java - java 除了EOF之外,有没有办法像C ++一样结束
问题描述
EOF是为C++本身定义的 但是如果JAVA中没有EOF呢?示例图片
解决方案
JavaInputStream#read
将完全如此,返回 -1 (C/C++) EOF 或字节范围内的其他 int,无符号为 0 .. 255。
但是,Java 中的String
(带有Reader
and Writer
)是针对 Unicode 文本的,char
它是一个 2 字节的 UTF16 值。Input-
and用于二进制数据,需要一些编码 ( OutputStream
)将其转换为.byte
Charset
String
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.
}
推荐阅读
- spring - 使用 `JdbcChannelMessageStore` 时防止自动创建或删除表
- mysql - 查找坐标之间最近距离的 SQL 查询运行速度非常慢
- google-cloud-platform - 来自 bigquery 表的 DLP 数据扫描显示起始字节为空
- python - 对均值和离散参数的负二项式回归效应
- ruby-on-rails - Ransack:过滤器活动管理员中未定义的方法名称
- python - 如何从 pyspark 数据框中的日期时间中提取小时数?
- android - 当数据来自广播接收器时如何设置视图模型
- c# - 从 .NET Core 中的另一个 IP 地址发送 HTTP 请求
- javascript - 为每个数组项添加一个 Promise 到 `Promise.all()`
- html - 宽度,最大宽度不适用于