溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java的DataInputStream和DataOutputStream怎么使用

發(fā)布時間:2022-05-27 09:19:21 來源:億速云 閱讀:352 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Java的DataInputStream和DataOutputStream怎么使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Java的DataInputStream和DataOutputStream怎么使用”吧!

簡介

在 io 包中,提供了兩個與平臺無關(guān)的數(shù)據(jù)操作流:數(shù)據(jù)輸出流(DataOutputStream)、數(shù)據(jù)輸入流 (DataInputStream)。

通常數(shù)據(jù)輸出流會按照一定的格式將數(shù)據(jù)輸出,再通過數(shù)據(jù)輸入流按照一定的格式將數(shù)據(jù)讀入。DataOutputStream 和 DataOutputStream 用來讀寫固定字節(jié)格式數(shù)據(jù)。

DataOutputStream

創(chuàng)建對象

DataOutputStream out = new DataOutputStream(相接的流)

方法將一個 int 類型的數(shù)據(jù)寫到數(shù)據(jù)輸出流中,底層將 4 個字節(jié)寫到基礎(chǔ)輸出流中

writeInt(int i)

將一個 double 類型的數(shù)據(jù)寫到數(shù)據(jù)輸出流中,底層會將 double 轉(zhuǎn)換成 long 類型,寫到基礎(chǔ)輸出流中,輸出8個字節(jié)

writeDouble(double d)

以機(jī)器無關(guān)的方式使用 utf-8 編碼方式將字符串寫到基礎(chǔ)輸出流中。先輸出 2 個字節(jié)表示字符串的字節(jié)長度,再輸出這些字節(jié)值

writeUTF()

DataInputStream

創(chuàng)建對象

DataInputStream dis = new DataInputStream(InputStream in);

方法從數(shù)據(jù)輸入流中讀取一個 int 類型數(shù)據(jù),讀取 4 個字節(jié)

readInt()

讀取8個字節(jié)

readDouble()

先讀取 2 個字節(jié)來確定字符串的字節(jié)長度,再讀取這些字節(jié)值

readUTF()

Tips:讀取結(jié)束,再讀取會出現(xiàn)EOFException

栗子1:寫入數(shù)據(jù)

public class Main {
    public static void main(String[] args) throws Exception {
        DataOutputStream out = new DataOutputStream(new FileOutputStream("d:/abc/f5"));
        out.writeInt(20211011);
        out.writeUTF("晴,18度");
        out.writeInt(20211012);
        out.writeUTF("晴,19度");
        out.writeInt(20211013);
        out.writeUTF("多云,17度");
        out.close();
    }
}

運(yùn)行結(jié)果:

Java的DataInputStream和DataOutputStream怎么使用

栗子2:讀取

public class Main {
    public static void main(String[] args) throws Exception {
        DataInputStream in = new DataInputStream(new FileInputStream("d:/abc/f5"));
        try {
            while (true) {
                int date = in.readInt();
                String s = in.readUTF();
                System.out.println(date);
                System.out.println(s);
            }
        } catch (EOFException e) {
            //正確讀取結(jié)束,不需要處理
        }
        in.close();
    }
}

運(yùn)行結(jié)果:

Java的DataInputStream和DataOutputStream怎么使用

栗子3:保存學(xué)生信息

要求用如下格式保存學(xué)生信息

學(xué)號 00 00 00 01
姓名 00 03 61 62 63
性別 00 61
年齡 00 00 00 16

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">
    <EditText
        android:id="@+id/et1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="學(xué)號" />
    <EditText
        android:id="@+id/et2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="姓名" />
    <EditText
        android:id="@+id/et3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="性別" />

    <EditText
        android:id="@+id/et4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="年齡" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存" />
    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="讀取" />
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />
</LinearLayout>

java

public class IoActivity extends AppCompatActivity {
    private EditText et1;
    private EditText et2;
    private EditText et3;
    private EditText et4;
    private Button btn1;
    private Button btn2;
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_io);
        setViews();
        setListeners();
    }
    private void setViews() {
        et1 = findViewById(R.id.et1);
        et2 = findViewById(R.id.et2);
        et3 = findViewById(R.id.et3);
        et4 = findViewById(R.id.et4);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        tv = findViewById(R.id.tv);
    }
    private void setListeners() {
        btn1.setOnClickListener(view -> baocun());
        btn2.setOnClickListener(view -> duqu());
    }
    private void baocun() {
        //IO操作有IO異常,所以進(jìn)行try...catch...
        /*
         *
         *           ┌DataOutputStream
         *    ┌FileOutputStream
         * sdcard
         */
        try {
            int id = Integer.parseInt(et1.getText().toString());
            String name = et2.getText().toString();
            String gender = et3.getText().toString();
            int age = Integer.parseInt(et4.getText().toString());

            DataOutputStream out = new DataOutputStream(
                    new FileOutputStream(getExternalFilesDir(null) + "/stu.txt", true)
            );
            out.writeInt(id);
            out.writeUTF(name);
            out.writeChar(gender.charAt(0));
            out.writeInt(age);
            out.close();

            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "保存失敗", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private void duqu() {
        //IO操作有IO異常,所以進(jìn)行try...catch...
        try {
            DataInputStream in = new DataInputStream(
                    new FileInputStream(getExternalFilesDir(null) + "/stu.txt")
            );

            try {
                tv.setText("");
                while (true) {
                    int id = in.readInt();
                    String name = in.readUTF();
                    char gender = in.readChar();
                    int age = in.readInt();
                    tv.append("id:" + id + "\n" + "name:" + name + "\n" + "gender:" + gender + "\n" + "age:" + age + "\n");
                }
            } catch (EOFException e) {

            }
            in.close();
            Toast.makeText(this, "讀取成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "讀取失敗", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

運(yùn)行程序:

Java的DataInputStream和DataOutputStream怎么使用

點(diǎn)擊讀取按鈕:

Java的DataInputStream和DataOutputStream怎么使用

其中getExternalFilesDir(null)得到以下路徑

/storage/emulated/0/Android/data/yourPackageName/files

這個目錄會在應(yīng)用被卸載的時候刪除,而且訪問這個目錄不需要動態(tài)申請STORAGE 權(quán)限。

所以運(yùn)行程序會在這個路徑下生成一個 stu.txt 的文件

到此,相信大家對“Java的DataInputStream和DataOutputStream怎么使用”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI