JAVA伊奥。Java中的DataInputStream类|集1

A. 数据输入流 使应用程序能够读取 基本Java数据类型 以独立于机器的方式(而不是原始字节)从底层输入流中。这就是为什么它被称为DataInputStream——因为它读取数据(数字),而不仅仅是字节。

null

应用程序使用数据输出流来写入数据,这些数据稍后可以由数据输入流读取。数据输入流和数据输出流以对UTF-8稍加修改的格式表示Unicode字符串。对于多线程访问,DataInputStream不一定是安全的。线程安全是可选的,由此类方法的用户负责。

首先让我们来讨论这个类的构造函数

建造师 执行的动作
DataInputStream(InputStream in) 创建使用指定基础InputStream的DataInputStream。

现在,让我们讨论这个类的方法,这些方法以表格形式在下面描述,如下所示:

方法 执行的动作
读取(字节[]b) 从包含的输入流中读取一定数量的字节,并将其存储到缓冲区数组b中。
读取(字节[]b,整数关闭,整数长度) 从包含的输入流中读取最长字节的数据到字节数组中。
readBoolean() 读取一个输入字节,如果该字节为非零,则返回true;如果该字节为零,则返回false。
readChar() 读取两个输入字节并返回一个字符值。
readUTF() 从底层输入流读取数据,并将字节转换为Unicode字符串。
readByte() 读取一个输入字节并返回一个字节值。
readFloat() 读取四个输入字节并返回一个浮点值。
准备好了 读取的字节数等于字节数组的长度
readDouble() 读取八个输入字节并返回一个双精度值。
readInt() 读取四个输入字节并返回一个int值。
readLine() 阅读一行行文字
readLong() 读取八个输入字节并返回一个长值
readShort() 读取两个输入字节并返回一个短值。
readUnsignedByte() 读取字节并作为整数返回
readUnsignedShort() 读取两个输入字节并作为整数数组返回
skipBytes() 从输入流跳过n字节的数据

记得: DataInputStream类通常与 数据输出流。

实施:

现在让我们来实现上面讨论过的这个类的一些方法

下面的程序使用try with资源。它需要JDK 7或更高版本,因为try-catch块的概念是在Java7中引入的

例1

JAVA

// Java program to Demonstrate DataInputStream Class
// Importing I/O classes
import java.io.*;
// Main class
class DataInputStreamDemo {
// Main driver method
public static void main(String args[]) throws IOException {
// Writing the data
// Try block to check for exceptions
try ( DataOutputStream dout =
new DataOutputStream( new FileOutputStream( "file.dat" )) ) {
dout.writeDouble( 1.1 );
dout.writeInt( 55 );
dout.writeBoolean( true );
dout.writeChar( '4' );
}
// Catch block to handle the exceptions
catch (FileNotFoundException ex) {
// Display message when FileNotFoundException occurs
System.out.println( "Cannot Open the Output File" );
return ;
}
// Reading the data back.
// Try block to check for exceptions
try ( DataInputStream din =
new DataInputStream( new FileInputStream( "file.dat" )) ) {
// Illustrating readDouble() method
double a = din.readDouble();
// Illustrating readInt() method
int b = din.readInt();
// Illustrating readBoolean() method
boolean c = din.readBoolean();
// Illustrating readChar() method
char d = din.readChar();
// Print the values
System.out.println( "Values: " + a + " " + b + " " + c + " " + d);
}
// Catch block to handle the exceptions
catch (FileNotFoundException e) {
// Display message when FileNotFoundException occurs
System.out.println( "Cannot Open the Input File" );
return ;
}
}
}


输出:

图片[1]-JAVA伊奥。Java中的DataInputStream类|集1-yiteyi-C++库

请注意,现在不再有任何显式的close()方法调用。try-with-resources结构解决了这个问题。 下一篇文章: JAVA伊奥。Java |集合2中的DataInputStream类 本文由 尼森特·夏尔马 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享