Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何覆盖文本文件中的一行?_Java - Fatal编程技术网

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

Java 如何覆盖文本文件中的一行?,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 fileWr

我想知道如何在我的文本文件中覆盖一行代码,我正在创建高分,我想知道如何覆盖代码行以更改所有分数的最高难度评级。现在我正在使用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
String timeStamp=new-SimpleDateFormat(“HH:mm-mm/dd/yyyy”).format(Calendar.getInstance().getTime())//有时间说什么时候得分
文件编写器文件编写器;
双重困难;
缓冲写入程序缓冲写入程序;
public void printHighScores(字符串p1Name、长elapsedTime、int boardWidth、int boardLength、int mines、boolean avoidDoublePrint、文件highScores){
//将他们的分数写入文件
试一试{
//停止将在文件上多次打印的错误
如果(避免双重打印){
fileWriter=newfilewriter(highScores,true);//创建一个writer以写入文件highScores
bufferedWriter=new bufferedWriter(fileWriter);//也可以这样写
双bw=(双)板宽;
双bl=(双)板长;
双ms=(双)地雷;
难度等级=ms/(bl*bw)*100;//根据每平方米的地雷数,在1-10的范围内找到难度等级
DecimalFormat dec=新的DecimalFormat(“#.####”);//格式为2个小数
bufferedWriter.write(“+p1Name+”:“+elapsedTime+”秒)在(“+boardWidth+”X“+boardLength+”)网格上,使用“+mines+”Mine(s)DR:“+dec.format(Hardicultyrating)+”%”;//将其写入文件
bufferedWriter.newLine();
bufferedWriter.write(时间戳);
bufferedWriter.newLine();
bufferedWriter.newLine();
bufferedWriter.close();//关闭文件写入
System.out.println(“完成”);//用于测试
avoidDoublePrint=false;//使其在结束if语句时不会打印两次
}
}捕获(异常e){//如果发生错误
System.out.println(“由于高分打印导致的错误”);
}//捕获结束
试一试{
BufferedReader br=新的BufferedReader(新的文件阅读器(“highScores.txt”);
String line=br.readLine();
while(行!=null){
对于(int i=0;i<30;++i){
br.readLine();
如果(i==3){
line=br.readLine();
最高两倍=最高两倍的值(行);
系统输出打印项次(最高);
系统输出打印LN(打印困难);
如果(难度>最高){
bufferedWriter.write(“+难处理+”);
}
}
}
}
br.close();
}捕获(例外e){
}
}//打印结束高分

}

您说要覆盖文件中的一行,但我看不到您将光标或其他任何内容放在何处

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

  • 读入文件
  • 解析并修改结果字符串
  • 写回新字符串
  • 到目前为止,一切都很好

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

    bufferedWriter.write(""+p1Name+": "+elapsedTime+" Second(s) on a ("+boardWidth+" X "+boardLength+") grid with "+mines+" Mine(s) DR: "+dec.format(difficultyRating)+"%");
    
    您想如何确定现在必须更换哪一行

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

    玩家名称;时间董事会;等


    也许这可以帮助:

    示例文本文件:

    John : 1000 Second(s) on a (100X100) grid with 2 Mine(s) DR: 10.00%
    06:34:23
    
    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%");
    }
    
    (2排)

    功能:

    John : 1000 Second(s) on a (100X100) grid with 2 Mine(s) DR: 10.00%
    06:34:23
    
    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%");
    }
    

    “DR:.*%”
    要从
    DR:10.00%
    更改为
    DR:25.5%

    请说明您正在尝试做什么。您想覆盖某一特定位置的一行还是最后写入的一行?基本上,您需要读取整个文件并替换所需的行,然后重新写入。现在你可以“聪明”并在阅读旧文件时将内容写入新文件,更新需要更新的行,删除旧文件并将新文件重命名到原来的位置…特洛伊木马,我正在尝试在特定位置覆盖