java - 在 Java 中使用 FileInputStream 从文件中读取文本时出现问题
问题描述
我的系统中有一个文件 input.txt,我想使用 Java 中的 FileInputStream 从该文件中读取数据。代码中没有错误,但仍然无法正常工作。它不显示输出。这是代码,任何人都可以帮助我。
package com.company;
import java.io.FileInputStream;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
// write your code here
byte[] array = new byte[100];
try {
InputStream input = new FileInputStream("input.txt");
System.out.println("Available bytes in the file: " + input.available());
// Read byte from the input stream
input.read(array);
System.out.println("Data read from the file: ");
// Convert byte array into string
String data = new String(array);
System.out.println(data);
// Close the input stream
input.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
解决方案
使用实用程序类Files
。
Path path = Paths.get("input.txt");
try {
String data = Files.readString(path, Charset.defaultCharset());
System.out.println(data);
} catch (Exception e) {
e.printStackTrace();
}
对于二进制数据,非文本,应该使用Files.readAllBytes
.
available()
不是文件长度,只是系统已经缓冲的字节数;read more 将在物理读取磁盘设备时阻塞。String.getBytes(Charset)
并new String(byte[], Charset)
明确指定实际字节的字符集。String
然后将文本保留为 Unicode,因此它可以组合世界上所有的脚本。由于当时使用 C 和 C++ 的情况,Java 被设计为使用 Unicode 文本。因此,您可以在字符串中混合使用阿拉伯文、希腊文、中文和数学符号。对于该二进制数据(
byte[], InputStream, OutputStream
),必须给定编码、Charset、字节所在的字节,然后将文本(String, char, Reader, Writer
) 转换为 Unicode。FileInputStream.read(byte[])
需要使用结果并且只读取一个缓冲区,必须重复。
推荐阅读
- servicestack - 持久化 RefreshToken OnAuthenticated - ServiceStack
- java - 在 SQLite 中显示具有给定 id 的行(SELECT WHERE 语句)不起作用 Android Studio
- android - Android Firebase 实时数据库:如何在实时数据库中加载图像并在 imageview 中检索它
- .htaccess - 从我的 .htaccess 文件中的 HTTPS 中删除单个链接
- c++ - 为什么 C++ 中的 OpenSSL 产生与命令行不同的输出
- javascript - 如何创建一个简单的 Angular 表单来获取包含刚刚更改的字段的对象
- javascript - 拆分数组中的元素并添加换行符,然后加入 - Javascript
- javascript - Bluebird - TypeError:无法读取未定义的属性“then”
- r - 运行 Rcpp 时 R Studio 崩溃
- xcode10 - 使用 xcodebuild 10 beta 运行 xcodebuild 测试时,如何解决“意外的重复创建者”?