各位GGJJ,下面是我从网上copy后修改的计数器bean,可以运行,但是其中保存记录的文件经常会自动清空,请问是怎么回事啊?!//counter.java 读写文件的一个bean
package com.dhcc.net;
import java.io.*;public class counter extends Object {
private String currentRecord = null;//保存文本的变量
private BufferedReader file; //BufferedReader对象,用于读取文件数据
private String path;//文件完整路径名
public counter() {
}
//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 = "0";
else
{//文件不为空
returnStr =currentRecord;
}
//返回读取文件的数据
return returnStr;
}
//ReadFile方法用来将数据counter+1后写入到文本文件filePath中
//以实现计数增长的功能
public void WriteFile(String filePath,String counter) throws FileNotFoundException
{
path = filePath;
//将counter转换为int类型并加一
int Writestr = Integer.parseInt(counter)+1;
System.out.println("Writestr:"+Writestr);
try {
//创建PrintWriter对象,用于写入数据到文件中
PrintWriter pw = new PrintWriter(new FileOutputStream(filePath));
//用文本格式打印整数Writestr
pw.println(Writestr);
//清除PrintWriter对象
pw.close();
} catch(IOException e) {
//错误处理
System.out.println("写入文件错误"+e.getMessage());
}
}}

解决方案 »

  1.   

    给个例子参考一下:
    import java.io.*;
    public class TestFile2
    {
     public static void main(String[] args) throws IOException
     {
      FileReader fr = new FileReader("ming.txt");
      char[] buffer = new char[1024];
      int ch = 0;
      while((ch = fr.read())!=-1 )
      {
       System.out.print((char)ch); 
      }
      
      InputStreamReader isr = new InputStreamReader(new FileInputStream("ming.txt"));
      while((ch = isr.read())!=-1)
      {
       System.out.print((char)ch); 
      } 
      
      BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));
      String data = null;
      while((data = br.readLine())!=null)
      {
       System.out.println(data); 
      }
      
      FileWriter fw = new FileWriter("hello.txt");
      String s = "hello world";
      fw.write(s,0,s.length());
      fw.flush();
      
      OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2.txt"));
      osw.write(s,0,s.length());
      osw.flush();
      
      PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true);
      pw.println(s);
      
      fr.close();
      isr.close();
      br.close();
      fw.close();
      osw.close();
      pw.close();
     } 
    }
      

  2.   

    可能是你调用WriteFile时传入的值不对