1

首先,我是 Java 新手。我给自己设定了一个小项目,但我目前陷入困境。我正在尝试写入一个已经存在的文件,但它只是覆盖它。我正在尝试替换包含“maxBooks”的行。

这是我使用的代码:

FileWriter writeFile = new FileWriter(fileLocation);
            BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
            BufferedWriter writeLines = new BufferedWriter(writeFile);

            System.out.println("\n-----File Begin-----");

            while((finalLines = readLines.readLine()) != null){

                if(finalLines.contains("maxBooks")){
                    writeLines.newLine();
                    writeLines.write(finalLines);

                    System.out.println("This is the if statement");
                    System.out.println(finalLines);
                } else {
                    fileLines.add(new String(finalLines));
                    System.out.println("This is the else statement");
                    System.out.println(finalLines);
                }
            }

            System.out.println("------File End------");

请记住,我忽略了尝试和捕捉。请让我知道如何编辑文本文件。如果您需要更多信息,请告诉我

谢谢 :)

编辑

对不起,我应该澄清一下。我只是想编辑测试文件中的 1 行,而不是整个文本文件。

最终代码:

FileWriter writeFile = new FileWriter(fileLocation + ".tmp", true);
            BufferedWriter writeLines = new BufferedWriter(writeFile);

            BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));


            System.out.println("\n-----File Begin-----");

            while((finalLines = readLines.readLine()) != null){

                if(finalLines.contains("maxBooks")){
                    writeLines.write("maxBooks = " + maxBooks);
                    writeLines.newLine();

                    System.out.println("This is the if statement");
                    System.out.println(finalLines);
                } else {
                    fileLines.add(new String(finalLines));
                    System.out.println("This is the else statement");
                    writeLines.write(finalLines);
                    writeLines.newLine();
                }
            }

            System.out.println("------File End------");

            file2.renameTo(file);

            writeLines.close();
4

2 回答 2

3

您覆盖了您尝试读取的文件,这是不好的做法。写入新文件,然后重命名为原始文件。

于 2013-05-19T18:36:00.880 回答
0

你读和写的fileLocation时候应该给两个不同的位置;

像这样

//define newLocation as string that contain path for new file to be written    
FileWriter writeFile = new FileWriter(newLocation);
                BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
                BufferedWriter writeLines = new BufferedWriter(writeFile);
于 2013-05-19T18:56:04.570 回答