• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

java之 ------ 文件的输入、输出(一)

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);
        short i=0,j=1;
        do
        {
            dout.writeInt(i);                              //向输出流写入一个整数
            dout.writeInt(j);
            i = (short)(i+j);
            j = (short)(i+j);
        } while (i>0);
        dout.close();                                      //先关闭数据流
        fout.close();                                      //再关闭文件流
    }

    public void readFromFile() throws IOException          //从指定文件里读取整数
    {
        FileInputStream fin = new FileInputStream(this.filename);
        DataInputStream din = new DataInputStream(fin);
        System.out.println(this.filename+":");
        while (true)                                       //输入流未结束时
            try
            {
                int i = din.readInt(); //从输入流中读取一个整数
                System.out.print(i+"  ");
            }
            catch (EOFException e)
            {
                break;
            }
        din.close();                                       //先关闭数据流
        fin.close();                                       //再关闭文件流
    }

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


/*
程序执行结果例如以下:
FibIntFile.dat:
0  1  1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181  6765  10946  17711  28657  

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

*/

posted on 2017-07-19 08:37  cynchanpin  阅读(261)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3