⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 intfile.java

📁 这是《Java2程序设计实用教程(第2版)》教材中附带的例题源代码。
💻 JAVA
字号:
//【例9.3】  将Fibonacci序列值写入一个整数类型文件中。

import java.io.*;

public class IntFile 
{
    private String filename;
    
    public IntFile(String filename)
    {
        this.filename = filename;
    }
    
    public void writeToFile() throws IOException           //将Fibonacci序列值写入指定文件
    {
        FileOutputStream fout = new FileOutputStream(this.filename);
        DataOutputStream dout = new DataOutputStream(fout);

        int i=0,j=1,count=0;
        while (count<20)
        {
            dout.writeInt(i);                              //向输出流写入一个整数
            dout.writeInt(j);
            i = i + j;
            j = i + j;
            count += 2;
        }
        dout.close();                                      //先关闭数据流
        fout.close();                                      //再关闭文件流
        System.out.println("Write Fibonacci to File "+this.filename);
    }

    public void readFromFile() throws IOException          //从指定文件中读取整数
    {
        FileInputStream fin = new FileInputStream(this.filename);
        DataInputStream din = new DataInputStream(fin);

        System.out.println("readFromFile "+this.filename);

        while (true)                                       //输入流未结束时
            try
            {
                int i = din.readInt();                     //从输入流中读取一个整数
                System.out.print(i+"  ");
            }
            catch (EOFException ioe)
            {
                break;
            }

        System.out.println();
        din.close();                                       //先关闭数据流
        fin.close();                                       //再关闭文件流
    }

    public static void main(String args[]) throws IOException
    {
        IntFile afile = new IntFile("FibIntFile.dat");
        afile.writeToFile();
        afile.readFromFile();
    }
}


/*
程序运行结果如下:
Write Fibonacci to File FibIntFile.dat 
readFromFile FibIntFile.dat
 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

程序设计错误说明如下:
1、readInt()方法到达输入流末尾时,抛出EOFException异常。

*/

⌨️ 快捷键说明

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