在特定行上写入txt文件时出现问题

时间:2018-11-10 22:09:56

标签: java javafx text-files

Student.txt

1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman

运行我的代码后,我会这样做:

Student.txt

1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman,2,3,1,3,4,6

但是我想,如果我搜索ID=2,请转到第二行并输入数字,如下所示:

Student.txt

1,Giannis,Oreos,Man
2,Maria,Karra,Woman,2,3,1,3,4,6
3,Maria,Oaka,Woman

代码:

@FXML 
TextField ID1,glossa,math,fis,xim,prog,gym;

@FXML
public void UseAddLesson() throws IOException{
    Scanner x = new Scanner("src/inware/students.txt");

    FileWriter fW = new FileWriter("src/inware/students.txt",true);
    BufferedWriter bW = new BufferedWriter(fW);

    boolean found= false;

    while(!found){
        String line = x.nextLine();
        if(line.contains(ID1.getText())){
            bW.write(","+glossa.getText()+",");
            bW.write(math.getText()+",");
            bW.write(fis.getText()+",");
            bW.write(xim.getText()+",");
            bW.write(prog.getText()+",");
            bW.write(gym.getText());
            System.out.println(line);
            found= true;
        }
    }
    bW.close();
    fW.close();
    x.close();
}

1 个答案:

答案 0 :(得分:0)

请勿尝试同时读取/写入同一文件。您也不能追加/覆盖文本文件的结构,要求插入点之后的所有文本都写在不同的位置。

我建议创建一个临时文件,然后用完成的新文件替换旧文件:

@FXML
public void UseAddLesson() throws IOException{
    String searchText = ID1.getText();
    Path p = Paths.get("src", "inware", "students.txt");
    Path tempFile = Files.createTempFile(p.getParent(), "studentsTemp", ".txt");
    try (BufferedReader reader = Files.newBufferedReader(p);
            BufferedWriter writer = Files.newBufferedWriter(tempFile)) {
        String line;

        // copy everything until the id is found
        while ((line = reader.readLine()) != null) {
            writer.write(line);
            if (line.contains(searchText)) {
                writer.write(","+glossa.getText()+",");
                writer.write(math.getText()+",");
                writer.write(fis.getText()+",");
                writer.write(xim.getText()+",");
                writer.write(prog.getText()+",");
                writer.write(gym.getText());
                break;
            }
            writer.newLine();
        }

        // copy remaining lines
        if (line != null) {
            writer.newLine();
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
        }
    }

    // copy new file & delete temporary file
    Files.copy(tempFile, p, StandardCopyOption.REPLACE_EXISTING);
    Files.delete(tempFile);
}

注意:如果您分发应用程序,则src目录可能不可用。