datastream.java

来自「JAVA 基础例题包含了JAVA常见的问题和常见的习题」· Java 代码 · 共 59 行

JAVA
59
字号
import java.io.*;
public class Datastream
{
    public static void main(String arg[])
    {
        String fname = "student1.dat";
        new Student1("Wang").save(fname);
        new Student1("Li").save(fname);
        Student1.display(fname);
    }
}    
class Student1 
{
    static int count=0;
    int number=1;
    String name;
    Student1(String n1)
    {
        this.count++;                        //编号自动加1
        this.number = this.count;
        this.name = n1;
    }
    Student1()
    {
        this("");
    }
    void save(String fname)
    {
        try
        {                                    //添加方式创建文件输出流
            FileOutputStream fout = new FileOutputStream(fname,true);
            DataOutputStream dout = new DataOutputStream(fout);
            dout.writeInt(this.number);
            dout.writeChars(this.name+"\n");
            dout.close();
        }
        catch (IOException ioe){}
    }
    static void display(String fname)
    {
        try
        {
            FileInputStream fin = new FileInputStream(fname);
            DataInputStream din = new DataInputStream(fin);
            int i = din.readInt();
            while (i!=-1)                    //输入流未结束时
            {
                System.out.print(i+"  ");
                char ch ;
                while ((ch=din.readChar())!='\n') //字符串未结束时
                    System.out.print(ch);
                System.out.println();
                i = din.readInt();
            }
            din.close();
        }
        catch (IOException ioe){}
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?