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) 收藏 举报
                    
                
                
            
        
浙公网安备 33010602011771号