簡體   English   中英

在特定行上寫入txt文件時出現問題

[英]Problem to write on txt file on specific line

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();
}

不要嘗試同時讀取/寫入相同的文件。 您也不能追加/覆蓋文本文件的結構,要求插入點之后的所有文本都寫在不同的位置。

我建議創建一個臨時文件,然后用完成的新文件替換舊文件:

@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目錄可能不可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM