Java PushbackInputStream
类
原文:https://www.studytonight.com/java-file-io/java-pushbackinputstream-class
在本教程中,我们将学习 Java 中的PushbackInputStream c
类。这个类扩展了 FilterInputStream 类,并提供了在不中断输入流的情况下“查看”输入流的机制。这个类可以读一个已经读完的字节,并推回一个字节。
句法
这是推包InputStream
类的语法声明,这个类扩展了 FilterInputStream。
public class PushbackInputStream extends FilterInputStream
推回InputStream
类方法
推回输入流方法的所有方法都可以在下表中找到:
方法 | 描述 |
---|---|
int available() |
此方法用于返回可以从输入流中读取的字节数。 |
int read() |
此方法用于从输入流中读取下一个字节的数据。 |
void mark(int readlimit) |
此方法用于标记输入流中的当前位置。 |
long skip(long x) |
此方法用于跳过和丢弃 x 字节的数据。 |
void unread(int b) |
此方法用于通过将字节复制到推回缓冲区来推回字节。 |
void unread(byte[] b) |
此方法用于通过将字节数组复制到推回缓冲区来推回字节数组。 |
void reset() |
此方法用于重置输入流。 |
void close() |
此方法用于关闭输入流。 |
boolean markSupported() |
此方法用于检查位置是否标记。 |
推回输入流示例
在这个例子中,我们演示了available()
方法如何在推回InputStream
类中工作。这里我们已经声明了打印编写器,它将在控制台上给出输出。我们还使用 ByteArrayInputStream 在输入上创建了一个流,并且在创建推回InputStream
类的对象时,我们将这个流传递给了构造器。available()方法返回可以从此输入流中读取的字节数。在这个例子中,我们以18
为例,因为字符串"Hello Studytonight"
是18
的长度。
package studytonight;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.io.PushbackInputStream;
public class StudyTonight
{
public static void main(String args[])
{
try
{
PrintWriter writer = new PrintWriter(System.out, true);
String str = "Hello Studytonight";
byte arr[] = str.getBytes();
ByteArrayInputStream stream = new ByteArrayInputStream(arr);
PushbackInputStream push = new PushbackInputStream(stream);
writer.println("size of available bytes: " + push.available());
writer.close();
}
catch (Exception e) {
System.out.print("Error: "+e.toString());
}
}
}
可用字节大小:18
推回输入流示例
在这个例子中,我们实现了推回InputStream
类的 read()方法。这个 read()方法返回一个 0 到 255 的整数,这些整数对应于字符的 ASCII 码。在这里,我们创建了一个推回InputStream
类的对象,并调用读取方法,直到它到达流的末尾。
package studytonight;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.io.PushbackInputStream;
public class StudyTonight
{
public static void main(String args[])
{
try
{
PrintWriter writer = new PrintWriter(System.out, true);
String str = "Hello Studytonight";
byte arr[] = str.getBytes();
ByteArrayInputStream stream = new ByteArrayInputStream(arr);
PushbackInputStream push = new PushbackInputStream(stream);
int ch;
while((ch=push.read())!=-1)
{
writer.print((char)ch);
}
writer.println();
writer.close();
}
catch (Exception e) {
System.out.print("Error: "+e.toString());
}
}
}
你好,今晚学习
结论
在本文中,我们学习了推回InputStream
类。这个类扩展了 FilterInputStream 类,并提供了在不中断输入流的情况下“查看”输入流的机制。这个类可以读一个已经读完的字节,并推回一个字节。