欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

达内课程-DataInputStream/DataOutputStream

程序员文章站 2022-05-22 20:36:22
...

DataInputStream/DataOutputStream

读写固定字节格式数据

DataOutputStream

创建对象
DataOutputStream out = new DataOutputStream(相接的流)

方法
writeInt(int i)//输出4个字节
writeDouble(double d)//输出8个字节
……
writeUTF()//先输出2个字节表示字符串的字节长度,再输出这些字节值

DataInputStream

方法
readInt()//读取4个字节
readDouble()//读取8个字节
……
readUTF()//先读取2个字节来确定字符串的字节长度,再读取这些字节值

读取结束,再读取会出现EOFException

栗子

DataOutputStream out = new DataOutputStream(
        new FileOutputStream("d:/abc/f2")
        );

        out.writeInt(20171213);
        out.writeUTF("阴,13度");
        out.writeInt(20171214);
        out.writeUTF("晴,14度");
        out.writeInt(20171215);
        out.writeUTF("雨,15度");
        out.close();

输出结果

达内课程-DataInputStream/DataOutputStream

读取栗子

DataInputStream in = new DataInputStream(
        new FileInputStream("d:/abc/f2")
        );
        try{
            while(true){
                int date = in.readInt();
                String s = in.readUTF();
                System.out.println(date);
                System.out.println(s);
            }
        }catch(EOFException e){
            //正确读取结束,不需要处理
        }
        in.close();

输出结果

20171213
阴,13度
20171214
晴,14度
20171215
雨,15度

练习:保存学生信息
用如下格式保存学生信息

学号 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"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@android:color/white"
              android:orientation="vertical"
              tools:context=".MainActivity">

    <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" />

</LinearLayout>

java

public class MainActivity extends Activity {

    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_main);
        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(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                baocun();
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View 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(Environment.getExternalStorageDirectory()+"/stu",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(Environment.getExternalStorageDirectory()+"/stu")
            );

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

TIP
1、现在我们想在模拟机的中读写数据
相关文章查看模拟机中路径怎么写

2、保存失败,显示的错误信息为 Permission denied
达内课程-DataInputStream/DataOutputStream

所以在AndroidMenifest.xml中添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

并在模拟机中,打开应用的权限

达内课程-DataInputStream/DataOutputStream

再次运行程序,显示保存成功

达内课程-DataInputStream/DataOutputStream

从模拟机中把stu文件导出至桌面,查看内容
保存了3个学生信息
达内课程-DataInputStream/DataOutputStream

点击读取,读取信息

达内课程-DataInputStream/DataOutputStream

相关标签: stream