如何覆盖文本文件中的单行?

时间:2013-12-03 22:05:58

标签: java

我想知道如何在我的文本文件中覆盖一行代码,我正在创建高分,我想知道如何覆盖改变所有分数的最高难度等级的代码行。现在我正在使用bufferedWriter.write(“”+ difficultyRating +“”);但它不会覆盖以前的分数。

String timeStamp = new SimpleDateFormat("HH:mm MM/dd/yyyy").format(Calendar.getInstance().getTime());//gets time to say when the score was made
FileWriter fileWriter;
double difficultyRating;
BufferedWriter bufferedWriter;

public void printHighScores(String p1Name, long elapsedTime, int boardWidth, int boardLength, int mines, boolean avoidDoublePrint, File highScores){


            //writes to a file their score
            try{
                //stops error where it would print multiple times on file
                if(avoidDoublePrint){
                fileWriter = new FileWriter(highScores, true);//creates a writer to write in file highScores
                    bufferedWriter = new BufferedWriter(fileWriter);//also makes it so to write in
                double bw=(double) boardWidth;
                double bl=(double) boardLength;
                double ms=(double) mines;
                difficultyRating = ms/(bl*bw)*100;//finds the difficulty rating on a scale of 1-10 based on mines per square
                DecimalFormat dec = new DecimalFormat("#.##");//formats to 2 decimals
                    bufferedWriter.write(""+p1Name+": "+elapsedTime+" Second(s) on a ("+boardWidth+" X "+boardLength+") grid with "+mines+" Mine(s) DR: "+dec.format(difficultyRating)+"%");//writes this to file
                    bufferedWriter.newLine();
                    bufferedWriter.write(timeStamp);
                    bufferedWriter.newLine();
                    bufferedWriter.newLine();
                    bufferedWriter.close();//closes writing in file                                                 
                    System.out.println("Done");//for testing
                    avoidDoublePrint=false;//make it so that it will not print twice, as it ends the if statement
                }
            }catch (Exception e){//if an error occurs
                System.out.println("Error because of high score printing");
            }//end of catch

            try {
                BufferedReader br = new BufferedReader(new FileReader("highScores.txt"));        
                     String line = br.readLine();   
                    while (line != null) {
                            for(int i = 0; i < 30; ++i){
                            br.readLine();
                            if(i==3){
                                line = br.readLine();
                                double highest = Double.valueOf(line);
                                System.out.println(highest);
                                System.out.println(difficultyRating);
                                if(difficultyRating>highest){
                                    bufferedWriter.write(""+difficultyRating+"");
                                }
                            }
                          }

                        }

                    br.close();


                    } catch(Exception e){
                    }
        }//end of print high scores

}

2 个答案:

答案 0 :(得分:0)

你说你要覆盖文件中的一行,但我没有看到任何东西,你在哪里定位光标或其他任何东西。

MadProgrammer在你的问题评论中提到的方法应该是正确的方法:

  1. 读入文件
  2. 解析并修改生成的字符串
  3. 回写新字符串
  4. 到目前为止,非常好......

    我认为您在找到要替换的正确行时会遇到问题,因为您将此内容写入文件:

    bufferedWriter.write(""+p1Name+": "+elapsedTime+" Second(s) on a ("+boardWidth+" X "+boardLength+") grid with "+mines+" Mine(s) DR: "+dec.format(difficultyRating)+"%");
    

    您想如何确定现在必须更换哪一行?

    我建议您以CSV格式管理您的高分,这样您就可以轻松选择任何值来做任何您想做的事情:

      

    playername;时间; boardWith;等

答案 1 :(得分:0)

或许可以帮助你:

示例文本文件:

John : 1000 Second(s) on a (100X100) grid with 2 Mine(s) DR: 10.00%
06:34:23

(2排)

功能:

private static void ReplaceSingleLine(string path, string find, string replace)
{
    IEnumerable<string> n = File.ReadAllLines(path).Select(line => System.Text.RegularExpressions.Regex.Replace(line, find, replace));
    File.WriteAllLines(path, n);
}

执行:

static void Main(string[] args)
{
    string _path = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
    ReplaceSingleLine(_path + "\\test.txt", "DR: .*%", "DR: 25.5%");
}

use regex "DR: .*%"DR: 10.00%更改为DR: 25.5%