[学习公共库]计数器程序 |
麦林 发表于 2006/11/30 14:37:27 | 1 在Bean程序中建立方法:ReadFile(String filePath)为读取指定文件的内容,WriteFile(String filePath)为将内容写入文件.
2 读取指定文件的内容,代码如下: //ReadFile方法用来读取文件filePath中的数据,并返回这个数据 public String ReadFile(String filePath) throws FileNotFoundException{ path = filePath; //创建新的BufferedReader对象 file = new BufferedReader(new FileReader(path)); String returnStr =null; try{ //读取一行数据并保存到currentRecord变量中 currentRecord = file.readLine(); } catch (IOException e){ //错误处理 System.out.println("读取数据错误."); } if (currentRecord == null) //如果文件为空 returnStr = "没有任何记录"; else{ //文件不为空 returnStr =currentRecord; } //返回读取文件的数据 return returnStr; }
3 写入文件,代码如下: //WriteFile方法用来将数据counter+1后写入到文本文件filePath中实现计数增长 public void WriteFile(String filePath,String counter) throws FileNotFoundException{ path = filePath; //将counter转换为int类型并加一 int Writestr = Integer.parseInt(counter)+1; try { //创建PrintWriter对象,用于写入数据到文件中 PrintWriter pw = new PrintWriter(new FileOutputStream(filePath)); pw.println(Writestr); //用文本格式打印整数Writestr pw.close(); //清除PrintWriter对象 } catch(IOException e) { //错误处理 System.out.println("写入文件错误"+e.getMessage()); } }
|
|
|

.: 公告
|
« | September 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | | | | | |
|
.: 我的分类(专题)
|

.: 最新日志
.: 最新回复
|

blog名称:栗色?蓝色? 日志总数:449 评论数量:201 留言数量:37 访问次数:2262145 建立时间:2006年5月16日 |
|

.: 留言板
|

.: 链接
|

|