简体   繁体   English

如何更新或删除.txt文件中的特定行?

[英]How to Update or delete a specific line from a .txt file?

I already have methods to insert data in to a text file and search. 我已经有了将数据插入文本文件并进行搜索的方法。 now I want methods for 'updating' and 'deleting' a selected record. 现在,我需要“更新”和“删除”所选记录的方法。

this is what I have done so far, 这是我到目前为止所做的

private void InsertbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                             

    fileWriter = null;
    try {
        String phone = Phone.getText();
        String fname = Fname.getText();
        String lname = Lname.getText();
        String nic = NIC.getText();
        String city = City.getSelectedItem().toString();

        fileWriter = new FileWriter(file, true);
        fileWriter.append(phone + "|" + fname + "|" + lname + "|" + nic + "|" + city+ "|");
        fileWriter.append("\r\n");
        fileWriter.flush();
        JOptionPane.showMessageDialog(InsertGUI.this, "<html> " + phone + " <br> Successfully saved! </html>");

        Phone.setText(null);
        NIC.setText(null);
        Fname.setText(null);
        Lname.setText(null);
        City.setSelectedIndex(0);

    } catch (IOException ex) {
        Logger.getLogger(InsertGUI.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(InsertGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                             

    try {
        fileReader = new FileReader(file);
        BufferedReader br = new BufferedReader(fileReader);

        String selectedphone = SearchF.getText();

        String content = "";
        String temp = "";
        try {
            while ((temp = br.readLine()) != null) {
                content += temp;
            }
        } catch (IOException ex) {
            Logger.getLogger(UpdateGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        HashMap<String, String> map = new HashMap();
        StringTokenizer stringTokenizer = new StringTokenizer(content, "|");
        boolean found = false;
        while (stringTokenizer.hasMoreTokens()) {
            String phone = stringTokenizer.nextElement().toString();
            String fname = stringTokenizer.nextElement().toString();
            String lname = stringTokenizer.nextElement().toString();
            String nic = stringTokenizer.nextElement().toString();
            String city = stringTokenizer.nextElement().toString();

            if (phone.equalsIgnoreCase(selectedphone)) {

                Phone.setText(phone);
                NIC.setText(nic);
                Fname.setText(fname);
                Lname.setText(lname);
                switch (city) {
                    case "Ambalangoda":
                        City.setSelectedIndex(0);
                        break;
                    case "Ampara":
                        City.setSelectedIndex(1);
                        break;
                    case "Anuradhapura":
                        City.setSelectedIndex(2);
                        break;
                    case "Avissawella":
                        City.setSelectedIndex(3);
                        break;
                    case "Badulla":
                        City.setSelectedIndex(4);
                        break;
                    case "Balangoda":
                        City.setSelectedIndex(5);
                        break;
                    }
                found = true;

            }

        }
        if (!found) {
            JOptionPane.showMessageDialog(UpdateGUI.this, "Phone number not found!");
            Phone.setText(null);
            NIC.setText(null);
            Fname.setText(null);
            Lname.setText(null);
            City.setSelectedIndex(0);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(UpdateGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

can someone please help me with this? 有人可以帮我吗? I want methods for: 我想要以下方法:

private void UpdatebuttonActionPerformed(java.awt.event.ActionEvent evt) {

}
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

}

Thanks in advance! 提前致谢! :) :)

I give you an example that i found. 我给你一个我发现的例子。 In this example i will replace a string inside of a line. 在此示例中,我将替换行内的字符串。 You can see that in my case im reading from a txt. 您可以看到在我的情况下,我正在从txt阅读。

/****** / ******

public static void replaceSelected(String replaceWith, String type) {
    try {
        // input the file content to the String "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        String line;String input = "";

        while ((line = file.readLine()) != null) input += line + '\n';

        file.close();

        System.out.println(input); // check that it's inputted right

        // this if structure determines whether or not to replace "0" or "1"
        if (Integer.parseInt(type) == 0) {
            input = input.replace(replaceWith + "1", replaceWith + "0"); 
        }
        else if (Integer.parseInt(type) == 1) {
            input = input.replace(replaceWith + "0", replaceWith + "1");
        } 

        // check if the new input is right
        System.out.println("----------------------------------"  + '\n' + input);

        // write the new String with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(input.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

public static void main(String[] args) {
    replaceSelected("Do the dishes","1");    
}

*/ * /

Result: 结果:

Original: 原版的:

Original Text File Content: 原始文本文件内容:

Do the dishes0 Feed the dog0 Cleaned my room1 Output: 洗碗0喂狗0打扫房间1输出:

Do the dishes0 Feed the dog0 洗碗0喂狗0

Cleaned my room1 打扫我的房间1

Do the dishes1 Feed the dog0 Cleaned my room1 洗碗1喂狗0打扫房间1


Recent output: 最近的输出:

Do the dishes1 (HAS BEEN CHANGED) Feed the dog0 Cleaned my room1 洗碗1(已变)喂狗0打扫房间1


Maybe this example helps for you. 也许这个例子对你有帮助。

Regards! 问候!

Read data to string. 读取数据到字符串。 Use string.replace(forDelte,""). 使用string.replace(forDelte,“”)。 And then just rewrite to txt file. 然后只需重写为txt文件即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM