日期:2014-05-20  浏览次数:20773 次

菜鸟关于文件操作的问题...
在自己扫雷程序中写了一个当赢了的时候执行的方法,
目的是提示一个对话框,说你赢了,时间多少[实现已经]
[未实现]之后再判断result.txt中的数据,
如果当中数据少于10行则要求输入name.
并按照time从小到大的顺序将name+ ", "+time+ "; "+ "\n "插入适当的位置;
如果数据等于10行,则删掉time最大的那行,并按照time从小到大的顺序将name+ ", "+time+ "; "+ "\n "插入适当的位置;
===========================
刚刚接触JAVA的文件操作,我自己已经实现的那部分写入操作还是baidu好久才会的;
还有个问题就是try和catch是干嘛的啊?处理异常的吗?
=============以下方法的源代码==============

public   void   result(int   time){
      try{
        BufferedReader   bin=null;

        BufferedWriter   bout=null;

        File   resultFile   =   new   File( "result.txt ");  
        if(   !   resultFile.   exists()   ){  
resultFile.createNewFile();  
return;

        }
        FileReader   in   =   new   FileReader(resultFile);  
        FileWriter   out   =   new   FileWriter(resultFile,true);
        bin=new   BufferedReader(in);
        bout=new   BufferedWriter(out);
        JTextField   nameField   =   new   JTextField( "MagicWolf ");
        JTextField   info2Field   =   new   JTextField();
        JTextField   name2Field   =   new   JTextField( "大名: ");
        name2Field.setEditable(false);
        info2Field.setEditable(false);
        info2Field.setText( "你赢了!时间: "+Integer.toString(time));
     
          JPanel   panel4   =   new   JPanel();
            panel4.setLayout(new   BorderLayout());
            panel4.add(nameField,BorderLayout.CENTER);
            panel4.add(info2Field,BorderLayout.NORTH);
            panel4.add(name2Field,BorderLayout.WEST);
          JOptionPane.showMessageDialog(panel,panel4);
          String   name;
          name   =   nameField.getText();
          bout.write(name+ ", "+time+ "; "+ "\n ");
          bout.flush();

          in.close();
          out.close();
          }
catch(IOException   ee){}

          }


------解决方案--------------------
try catch 是异常处理的 因为文件操作可能会抛出异常



------解决方案--------------------
赫赫,基本上这是一个比较麻烦的问题。

基本思路如下,

首先读取filename文件到string数组,可用类BufferReader,FileReader

如果文件不存在File.exists,不做读入处理

如果文件存在读取失败,并且filename_bak存在,将filename_bak改名filename并且读入

关闭输入数据流

加入最新纪录

解析string数组取得time

排序

如存在删除旧filename_bak文件File.delete

生成新filename_bak文件

删除filename文件

做成filename文件,FileWriter

删除filename_bak文件