一、DataInputStream簡介
DataInputStream是Java IO包中的一個類,用於讀取二進制數據。它提供了一系列讀取不同數據類型(如int、byte、char等)的方法。該類包含在與輸入流相關的類中,因此常與FileInputStream等一起使用。
二、DataInputStream的構造函數
public DataInputStream(InputStream in)
該構造函數參數為輸入流,在使用DataInputStream的時候需要先定義一個輸入流。
三、DataInputStream的常用方法
1.read()
public final int read() throws IOException
該方法從輸入流中讀取下一個位元組,並返回位元組的值。如果已經到達流的末尾,則返回-1。
2.read(byte[] b, int off, int len)
public final int read(byte[] b, int off, int len) throws IOException
該方法從輸入流中讀取len個位元組的數據,並將其存儲在byte數組中,從off位置開始存儲。返回讀取到的位元組數。
3.readBoolean()
public final boolean readBoolean() throws IOException
該方法從輸入流中讀取1個位元組的數據,並返回一個布爾值。
4.readByte()
public final byte readByte() throws IOException
該方法從輸入流中讀取1個位元組的數據,並返回一個byte類型的值。
5.readChar()
public final char readChar() throws IOException
該方法從輸入流中讀取2個位元組的數據,並返回一個char類型的值。
6.readDouble()
public final double readDouble() throws IOException
該方法從輸入流中讀取8個位元組的數據,並返回一個double類型的值。
7.readFloat()
public final float readFloat() throws IOException
該方法從輸入流中讀取4個位元組的數據,並返回一個float類型的值。
8.readInt()
public final int readInt() throws IOException
該方法從輸入流中讀取4個位元組的數據,並返回一個int類型的值。
9.readLong()
public final long readLong() throws IOException
該方法從輸入流中讀取8個位元組的數據,並返回一個long類型的值。
10.readShort()
public final short readShort() throws IOException
該方法從輸入流中讀取2個位元組的數據,並返回一個short類型的值。
11.readUTF()
public final String readUTF() throws IOException
該方法從輸入流中讀取一個UTF格式的字符串,並返回一個字符串值。
四、DataInputStream的使用示例
下面的代碼演示了如何使用DataInputStream類讀取一個二進制文件中的int、double、boolean、UTF格式的字符串。
import java.io.*; public class DataInputStreamExample { public static void main(String[] args) { InputStream inputStream = null; DataInputStream dataInputStream = null; try { inputStream = new FileInputStream("test.dat"); dataInputStream = new DataInputStream(inputStream); //讀取int類型數據 int intData = dataInputStream.readInt(); System.out.println("讀取int類型數據:" + intData); //讀取double類型數據 double doubleData = dataInputStream.readDouble(); System.out.println("讀取double類型數據:" + doubleData); //讀取boolean類型數據 boolean booleanData = dataInputStream.readBoolean(); System.out.println("讀取boolean類型數據:" + booleanData); //讀取UTF格式字符串 String strData = dataInputStream.readUTF(); System.out.println("讀取UTF格式字符串數據:" + strData); } catch (IOException e) { e.printStackTrace(); } finally { try { inputStream.close(); dataInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
五、總結
使用DataInputStream可以方便地讀取二進制數據,並通過提供的各種方法讀取不同數據類型的值。在使用DataInputStream的時候應特別注意讀取數據的順序,不要出現讀取順序和存儲順序不一致的情況,否則將導致讀取到錯誤的數據。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/205811.html