Home  >  Article  >  Java  >  How to use Java's DataInputStream and DataOutputStream

How to use Java's DataInputStream and DataOutputStream

WBOY
WBOYforward
2023-04-28 18:40:161830browse

Introduction

In the io package, two platform-independent data operation streams are provided: data output stream (DataOutputStream) and data input stream (DataInputStream).

Usually the data output stream will output the data in a certain format, and then the data will be read in in a certain format through the data input stream. DataOutputStream and DataOutputStream are used to read and write fixed byte format data.

DataOutputStream

Create object

DataOutputStream out = new DataOutputStream(相接的流)

MethodWrite an int type data to the data output stream, the bottom layer will Write 4 bytes to the basic output stream

writeInt(int i)

Write a double type data to the data output stream. The bottom layer will convert the double into a long type and write it to the basic output stream to output 8 words. Section

writeDouble(double d)

Writes a string to the underlying output stream using UTF-8 encoding in a machine-independent manner. First output 2 bytes representing the byte length of the string, and then output these byte values

writeUTF()

DataInputStream

Create object

DataInputStream dis = new DataInputStream(InputStream in);

MethodRead an int type data from the data input stream, read 4 bytes

readInt()

Read 8 bytes

readDouble()

Read 2 words first section to determine the byte length of the string, and then read these byte values

readUTF()

Tips:The reading is completed, and an EOFException will occur when reading again

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

Run result:

How to use Javas DataInputStream and 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();
    }
}

Running result:

How to use Javas DataInputStream and DataOutputStream

Chestnut 3: Save student information

Required to save student information in the following format

Student number 00 00 00 01

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

Run the program:

How to use Javas DataInputStream and DataOutputStream##Click the read button:

How to use Javas DataInputStream and DataOutputStreamgetExternalFilesDir(null)

Get the following path

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

This directory will be deleted when the application is uninstalled, and accessing this directory does not require dynamic application for STORAGE permissions.

So running the program will generate a stu.txt file under this path

The above is the detailed content of How to use Java's DataInputStream and DataOutputStream. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete