Java 计数器Counter(一个FileReader ,FileWriter的例子)
2016-06-19 13:06
471 查看
创建Java Project而不是Java EE,
运行的时候也要选择 Java Application
main.java
Counter.java
运行结果:
Java计数器!Powered By 涵涵。
您是第13次使用本系统!
Hello World!
运行的时候也要选择 Java Application
main.java
package input; public class main { public static void main(String[] args) { // TODO Auto-generated method stub counter obj=new counter("D:/counter1.txt"); } }
Counter.java
/******************* * CopyRight(C)2016-6-19 13:02:55 * Author:邱于涵 * Java运行计数器的一个小程序 * Blog:http://blog.csdn.net/u012997311 * **********************/ package input; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class counter { private File m_File; //|构造函数 public counter(String filename){ m_File=null; //| this.InitFile(filename); this.ReaderCounter(); } //|创建文件(对象) private void InitFile(String filename) { System.out.println("Java计数器!Powered By 涵涵。"); this.m_File=new File(filename); //|判断文件是否存在 if(!this.m_File.exists()){ try{ this.m_File.createNewFile(); //|字符流 try{ FileWriter writer=new FileWriter(this.m_File); writer.write("0"); writer.close(); }catch(IOException e) { System.out.println(e.getMessage()); } }catch(IOException e) { System.out.println(e.getMessage()); } } } //|读取次数并且(递增)打印出来 private void ReaderCounter(){ //|读取 try{ FileReader in=new FileReader(this.m_File); /*************** * 判断文件的大小来申请相应的 char 数组 * ******************/ FileInputStream inputstream=new FileInputStream(this.m_File); int allBytes=inputstream.available(); /********************/ char [] buffer=new char[allBytes]; in.read(buffer); //|char[]转化成String int count=Integer.parseInt(String.valueOf(buffer)); //|关闭输入字符流 in.close(); //|叠加 ++count; //|输出字符流 FileWriter out=new FileWriter(this.m_File); //|int转化成 String 输出 out.write(String.valueOf(count)); out.close(); System.out.println("您是第"+count+"次使用本系统!"); System.out.println(); }catch(IOException e) { System.out.println(e.getMessage()); } System.out.println("Hello World!"); } }
运行结果:
Java计数器!Powered By 涵涵。
您是第13次使用本系统!
Hello World!
相关文章推荐
- java.HelloWorld
- java 成神之路 (一)
- Spring MVC过滤器-登录过滤
- Java千百问_02基本使用(011)_如何编写单线程Socket程序
- Java虚拟机(JVM)以及跨平台原理
- Spring MVC基本概念
- Java安全管理器——SecurityManager
- 使用JAXB类库实现XML与JAVA对象的互转
- JAVA 笔记
- 使用ol,添加图书销售排行榜
- Service中通过main方法加载Spring连接数据库等操作
- java中File类的使用方法
- SpringMVC i18n国际化资源文件路径配置
- struts2 标签库 /struts-dojo-tags not found&Expression parameters.parseContent is undefined
- Java开发实用工具及组件应用
- 依赖、关联、聚合、组合等之间的关系
- java基础知识:java项目的命名规范
- spring 切面配置
- java使用quartz执行任务调度
- Java集合框架的层次结构和使用规则梳理