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

How to use Java's DataInputStream and DataOutputStream

WBOY
Release: 2023-04-28 18:40:16
forward
1888 people have browsed it

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(相接的流)
Copy after login

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)
Copy after login

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)
Copy after login

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()
Copy after login

DataInputStream

Create object

DataInputStream dis = new DataInputStream(InputStream in);
Copy after login

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

readInt()
Copy after login

Read 8 bytes

readDouble()
Copy after login

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

readUTF()
Copy after login

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

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

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>
Copy after login

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();
        }
    }
}
Copy after login
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!

source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template