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 阅读(248) 评论(0) 编辑 收藏 举报
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步