首页 > 解决方案 > 编辑打开的 .txt 中的文件并用 Java 中的新数据替换它们的过程

问题描述

在我的代码中玩了一个游戏,但首先读取一个文件并将排行榜保存在链表中。玩完游戏后,得到一个分数,这个分数按照链表的顺序相加。我所要做的就是将这个新列表写入 txt 文件。

这是玩游戏前的清单。
Pelin;30
Kaan;15
Ali;50
Yeliz;25
Cem;40
Can;35
Ece;5
Sibel;30
Remzi;20
Nazan;10

这是我的链表节点类:

public class Node {
    private Object data;
    private Node link;

    public Node(Object dataToAdd) {
        data = dataToAdd;
        link = null;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Node getLink() {
        return link;
    }

    public void setLink(Node link) {
        this.link = link;
    }

}

这是我的 SLL 课程:

public class SingleLinkedList {
    Node head;

    public void insertScore(Object dataToAdd) {
        Node newNode = new Node(dataToAdd);
        if (head == null) {
            head = newNode;
        } else {
            int score = getScore(dataToAdd);
            int headObjectScore = getScore(head.getData());
            if (score > headObjectScore) {
                Node temp = head;
                head = newNode;
                newNode.setLink(temp);
            } else {
                Node currentNode = head;
                // to handle if the newNode has the biggest score
                if (currentNode.getLink() == null) {
                    currentNode.setLink(newNode);
                    currentNode = newNode;
                }
                while (currentNode.getLink() != null) {
                    Node oldNode = currentNode;
                    currentNode = currentNode.getLink();
                    if (score > getScore(currentNode.getData())) {
                        oldNode.setLink(newNode);
                        newNode.setLink(currentNode);
                        break;
                    }
                    // to handle if the newNode has the biggest score
                    if (currentNode.getLink() == null) {
                        currentNode.setLink(newNode);
                        currentNode = newNode;
                    }
                }

            }

        }
    }
private int getScore(Object data) {
        return Integer.valueOf(((String) data).split(";")[1]);
    }

我需要打印列表txt文件
在此处输入图像描述

我已完成管理高分表,但不知道如何使用新的链表更改 .txt 文件

标签: javafilesortinglinked-listfile-writing

解决方案


List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);

对于 Java 7+,您可以使用这种方式。下面的链接列出了几种在 Java 中创建文件并打印到它们的方法。考虑一下你写了多少以及它是否需要:

  1. 附加到现有文件
  2. 在新文件中并删除旧内容
  3. 在一个全新的文件中

来自Java 中的文件 IO


推荐阅读