简体   繁体   中英

How to update a txt file on java

I have a text file and I want to update everytime only the last 3 labels

The changes will be made via ID (1,2 etc.)

pg (for ID=1 change: 10,18/10/18,7 to 12,21/10/18,2)

User.txt:

1,alex,pass,Admin,Alexandros,Karatzas,Male,18/10/1990,A'Likeiou,Antreas,Karatzas,6945952301,10,18/10/18,7
2,maria,pass1,User,Maria,Karatza,Female,18/10/1990,B'Likeiou,Antreas,Karatzas,6945952381,20,18/10/18,5

So after run i want to take this as output:

1,alex,pass,Admin,Alexandros,Karatzas,Male,18/10/1990,A'Likeiou,Antreas,Karatzas,6945952301,12,21/10/18,2
2,maria,pass1,User,Maria,Karatza,Female,18/10/1990,B'Likeiou,Antreas,Karatzas,6945952381,20,18/10/18,5

The code searches for ID, reads-writes data but how can i replace the last 3 labels everytime?

Source Code:

    @FXML 
         TextField ID3,abs,Dabs,Fabs
    @FXML
    public void UseAddAbs() throws IOException {                //Kanei Add tis Apousies sinfona me to ID
        String searchText = ID3.getText();
        Path p = Paths.get("src", "inware", "users.txt");
        Path tempFile = Files.createTempFile(p.getParent(), "usersTemp", ".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("," + Fabs.getText());
                    writer.write("," + Dabs.getText());
                    writer.write("," + abs.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);
    }

Split the lines and work on fields:

        while ((line = reader.readLine()) != null) {
            String[] fields = line.split("[,]");
            if (fields[0].equals(searchID)) {
                fields[12] = "12";
                fields[13] = "21/10/18";
                fields[14] = "2";
            }
            writer.println(String.join(",", fields));
        }

Update: my code:

public static void main(String[] args) {
    try {
        String searchText = "1";
        Path p = Paths.get(".", "users.txt");
        Path tempFile = Files.createTempFile(p.getParent(), "usersTemp", ".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) {
                String[] fields = line.split("[,]");
                if (searchText.equals(fields[0])) {
                    for (int i = 0; i < fields.length; ++i) {
                        System.out.println(i + ": " + fields[i]);
                    }
                    fields[12] = "12";
                    fields[13] = "21/10/18";
                    fields[14] = "2";
                }
                writer.write(String.join(",", fields));
                writer.newLine();
            }
        }

        // copy new file & delete temporary file
        Files.copy(tempFile, p, StandardCopyOption.REPLACE_EXISTING);
        Files.delete(tempFile);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

You can split line into array and update last 3 array elements. Then all you have to do is build new line from that array and write this line instead of an old one.

Example:.

while ((line = reader.readLine()) != null) {
    if (line.contains(searchText)) {
        String updatedLine = updateLastNStrings(line, 3);
        writer.write(updatedLine);
        break;
    } else {
        writer.write(line);
    }
    writer.newLine();
}

private String updateLastNStrings(String line, int n) {
    String [] parts = line.split(",");
    for (int i = parts.length - n; i < parts.length; i++) {
        // update String
        String newPart = parts[i] + "_UPDATED";
        parts[i] = newPart;
    }
    return String.join(",", parts);
}

Input:

1,alex,pass,Admin,Alexandros,Karatzas,Male,18/10/1990,A'Likeiou,Antreas,Karatzas,6945952301,10,18/10/18,7
2,maria,pass1,User,Maria,Karatza,Female,18/10/1990,B'Likeiou,Antreas,Karatzas,6945952381,20,18/10/18,5

Result

1,alex,pass,Admin,Alexandros,Karatzas,Male,18/10/1990,A'Likeiou,Antreas,Karatzas,6945952301,12_UPDATED,21/10/18_UPDATED,2_UPDATED
2,maria,pass1,User,Maria,Karatza,Female,18/10/1990,B'Likeiou,Antreas,Karatzas,6945952381,20,18/10/18,5

Note updated String with _UPDATED

Note

Besides all that, the code you found is flawed, since to find ID it is searching if line contains a charSequence. What if ID is a content of a line?

Example:

1,some_content,2,3
2,some_content,1

You try to find a line by id 2 and first line will be updated instead of a second one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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