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

📄 textfile.java

📁 《Java2程序设计实用教程(第2版)》课件
💻 JAVA
字号:
//【例9.5】  将Fibonacci序列值写入一个文本文件中。

import java.io.*;

public class TextFile 
{
    private String filename;
    
    public TextFile(String filename)
    {
        this.filename = filename;
    }
    
    public void writeToFile() throws IOException           //将Fibonacci序列值写入指定文本文件
    {
        FileWriter fout = new FileWriter(this.filename);
        int i=0,j=1,count=0;
        while (count<20)
        {
            fout.write(i+"  "+j+"  ");                     //向文件字符输出流写入一个字符串
            i = i + j;
            j = i + j;
            count += 2;
            if (count % 10 == 0)
                fout.write("\r\n");                        //写入一个回车换行符
        }

        fout.close();
        System.out.println("Write Fibonacci to File "+this.filename);
    }

    public void readFromFile() throws IOException          //从指定文本文件中读取字符串
    {
        FileReader fin = new FileReader(this.filename);
        BufferedReader bin = new BufferedReader(fin);

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

        String aline = "";
        do
        {
            aline = bin.readLine();                        //读取一行字符串,输入流结束时返回null
            if (aline!=null)
                System.out.println(aline);
        }while (aline!=null);

        bin.close();
        fin.close();
    }

    public static void main(String args[]) throws IOException
    {
        TextFile afile = new TextFile("FibFile.txt");
        afile.writeToFile();
        afile.readFromFile();
    }
}


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


*/

⌨️ 快捷键说明

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