有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何覆盖文本文件中的一行?

我想知道如何覆盖文本文件中的一行代码,我正在创建高分,我想知道如何覆盖代码行,从而更改所有分数的最高难度评级。现在我正在使用bufferedWriter。写(“+”难句+”);但它不会覆盖之前的分数

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) 个答案

  1. # 1 楼答案

    也许这能帮上忙:

    示例文本文件:

    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: 10.00%变为DR: 25.5%

  2. # 2 楼答案

    你说你想覆盖文件中的一行,但我看不到什么,你把光标或其他东西放在哪里

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

    1. 读入文件
    2. 解析并修改结果字符串
    3. 写回新字符串

    到目前为止,很好

    但是我想你在找到正确的替换行时会遇到问题,因为你把这个写到了文件中:

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

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

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

    playername;time;boardWith;etc