Java中的逐字节输入函数
发布时间:2023-05-31 16:44:59
Java提供了许多逐字节输入函数,可以方便地读取二进制和文本文件中的数据。以下是常用的逐字节输入函数:
1. InputStream.read()
该函数从输入流中读取一个字节的数据,并返回其值。如果输入流已经到达末尾,则返回-1。
示例代码:
try {
InputStream inputStream = new FileInputStream("file.txt");
int data = inputStream.read();
while (data != -1) {
System.out.print((char) data);
data = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
2. InputStream.read(byte[] b)
该函数从输入流中读取一定数量的字节,并存储到byte数组b中。返回读取的字节数,如果到达末尾则返回-1。
示例代码:
try {
InputStream inputStream = new FileInputStream("file.txt");
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
while (length != -1) {
System.out.write(buffer, 0, length);
length = inputStream.read(buffer);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
3. DataInputStream.readByte()
该函数从输入流中读取一个字节的数据,并返回其值。如果输入流已经到达末尾,则抛出EOFException异常。
示例代码:
try {
InputStream inputStream = new FileInputStream("file.dat");
DataInputStream dataInputStream = new DataInputStream(inputStream);
while (true) {
byte data = dataInputStream.readByte();
System.out.print(data + " ");
}
} catch (EOFException e) {
System.out.println("End of file");
} catch (IOException e) {
e.printStackTrace();
}
4. RandomAccessFile.read()
该函数从输入流中读取一个字节的数据,并返回其值。如果输入流已经到达末尾,则返回-1。
示例代码:
try {
RandomAccessFile file = new RandomAccessFile("file.txt", "r");
long fileSize = file.length();
for (long i = fileSize - 1; i >= 0; i--) {
file.seek(i);
System.out.print((char) file.read());
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
总之,逐字节输入函数非常有用,可以帮助我们读取二进制和文本文件中的数据。但是需要注意,它们可能会比逐行输入函数更慢,特别是当需要读取大量数据时。因此,在处理大型文件时, 使用缓冲区和其他更高级的技术。
