ホームページ  >  記事  >  Java  >  JavaのDataInputStreamとDataOutputStreamの使い方

JavaのDataInputStreamとDataOutputStreamの使い方

WBOY
WBOY転載
2023-04-28 18:40:161782ブラウズ

はじめに

io パッケージでは、プラットフォームに依存しない 2 つのデータ操作ストリーム、データ出力ストリーム (DataOutputStream) とデータ入力ストリーム (DataInputStream) が提供されます。

通常、データ出力ストリームは特定の形式でデータを出力し、データはデータ入力ストリームを通じて特定の形式で読み込まれます。 DataOutputStream と DataOutputStream は、固定バイト形式のデータの読み取りと書き込みに使用されます。

DataOutputStream

オブジェクトの作成

DataOutputStream out = new DataOutputStream(相接的流)

メソッドint 型データをデータ出力ストリームに書き込みます。最下層は基本出力ストリームに 4 バイトを書き込みます

writeInt(int i)

データ出力ストリームに double 型のデータを書き込みます。最下層は double を long 型に変換し、それを基本出力ストリームに書き込み、8 ワードを出力します。セクション

writeDouble(double d)

マシンに依存しない方法で UTF-8 エンコーディングを使用して、基になる出力ストリームに文字列を書き込みます。最初に文字列のバイト長を表す 2 バイトを出力し、次にこれらのバイト値を出力します

writeUTF()

DataInputStream

Create object

DataInputStream dis = new DataInputStream(InputStream in);

メソッドデータ入力ストリームから int 型データを読み取り、4 バイトを読み取り

readInt()

8 バイトを読み取り

readDouble()

最初のセクションを 2 ワード読み取り、文字列のバイト長を決定します。次に、これらのバイト値を読み取ります

readUTF()

ヒント:読み取りが完了し、再度読み取るときに EOFException が発生します

Chestnut 1 :Write data

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();
    }
}

実行結果:

JavaのDataInputStreamとDataOutputStreamの使い方

## Chestnut 2: Read

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) {
            //正确读取结束,不需要处理
        }
        in.close();
    }
}

実行結果:

JavaのDataInputStreamとDataOutputStreamの使い方

チェスト 3: 学生情報の保存

学生情報を次の形式で保存するには必須です

学生番号 00 00 00 01

名前00 03 61 62 63
Gender00 61
Age00 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="学号" />
    <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异常,所以进行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异常,所以进行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();
        }
    }
}

実行プログラム:

JavaのDataInputStreamとDataOutputStreamの使い方

読み取りボタンをクリックします:

JavaのDataInputStreamとDataOutputStreamの使い方

getExternalFilesDir( null)

次のパスを取得します#/storage/emulated/0/Android/data/yourPackageName/files

このディレクトリは、アプリケーションが削除されると削除されます。アンインストールされており、このディレクトリへのアクセスには STORAGE 権限のための動的アプリケーションは必要ありません。

プログラムを実行すると、このパスに stu.txt ファイルが生成されます。

以上がJavaのDataInputStreamとDataOutputStreamの使い方の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。