章
目
录
Java InputStreamReader 类常用于从代表文本的字节中读取字符,从文件(或网络连接)中读取字符。在本Java教程中,我们将学习InputStreamReader类,它的创建和初始化,以及它的方法,这些方法可以帮助我们从源读取数据。
1.InputStreamReader 类
- 它充当字节流到字符流的桥梁。使用InputStreamReader,我们可以读取任何以字节为单位的文件并将其转换为所需字符集的字符。
- 它是java.io包的一部分。
- 它扩展了抽象类Reader。
- 它实现了Closeable,AutoCloseable和Readable接口。
- 它提供了从流中读取字符的方法。
2.创建 InputStreamReader
如前所述,InputStreamReader 读取文件时使用字节流并将其转换为字符流。这意味着我们必须首先创建一个InputStream,然后使用此 Reader 从该流中读取字符。
在下面给出的示例中,InputStreamReader 将从输入流 fis 中读取字符,该流反过来从文件 data.txt 中读取字节。
String file = "c:\temp\data.txt";
// 创建InputStream
FileInputStream fis = new FileInputStream(file);
// 创建 InputStreamReader
InputStreamReader isr = new InputStreamReader(fis);
3. 设置字符编码
如果从流中读取的字符使用不同的编码,则在 InputStreamReader 的构造函数中传递 Charset 信息。
String file = "c:\temp\data.txt";
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF8"));
4. 关闭 InputStreamReader
当我们完成从流的读取时,调用 inputStreamReader.close() 方法。或者,我们可以利用这个类的自动关闭功能。
在给定的示例中,try-with-resources 功能将在 try 块完全执行时自动关闭 InputStreamReader 和 FileInputStream。
String file = "c:\temp\data.txt";
try (InputStreamReader input
= new InputStreamReader(new FileInputStream(file))) {
//Perform operations
}
5.Java InputStreamReader 示例
让我们通过几个示例来看看如何使用Java中的InputStreamReader来读取文件。在每个示例中,我们将读取名为”demo.txt”的文件。
hello world 1
hello world 2
hello world 3
示例1:使用InputStreamReader读取文件
在给定的示例中,我们将读取文件”demo.txt”的所有内容并将其存储到一个字符数组中。然后,我们将读取的字符打印到标准输出。
我们应该使用这种方法来读取小文件。另外,不要忘记创建一个足够大的字符数组来存储文件中的所有字符。
read(char[])方法将字符读入给定的数组中。此方法将阻塞,直到有输入可用,发生I/O错误或达到流的末尾。
public class InputStreamReaderExample
{
public static void main(String[] args)
{
// Creates an array of character
char[] array = new char[50];
try (InputStreamReader input
= new InputStreamReader(new FileInputStream("demo.txt"))) {
// Reads characters from the file
input.read(array);
System.out.println(array);
}
catch (Exception e) {
e.getStackTrace();
}
}
}
输出:
hello world 1
hello world 2
hello world 3
示例2:使用InputStreamReader逐个字符地读取Java文件
在给定的示例中,我们将逐个字符地读取相同的文件。这可以用于读取更大的文件。
public class InputStreamReaderExample
{
public static void main(String[] args)
{
try (InputStreamReader input
= new InputStreamReader(new FileInputStream("demo.txt"))) {
int data = input.read();
while (data != -1)
{
//Do something with data e.g. append to StringBuffer
System.out.print((char) data);
data = input.read();
}
}
catch (Exception e) {
e.getStackTrace();
}
}
}
输出:
hello world 1
hello world 2
hello world 3