java - 编辑打开的 .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 文件
解决方案
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 中创建文件并打印到它们的方法。考虑一下你写了多少以及它是否需要:
- 附加到现有文件
- 在新文件中并删除旧内容
- 在一个全新的文件中
推荐阅读
- java - 使用二分搜索实现底平方根
- swift - 基于 ipad 或 iphone 改变对象的约束
- python - 我有 2 个函数做同样的事情,但是在调用这两个函数时,只有一个返回,而另一个不返回
- java - 是否可以让我的 JFrame 按钮不断打印输出
- javascript - Promise 函数不返回结果
- java - json格式正确的字符串,但我在转换时仍然出错
- stata - 汉字是.dta文件中的问号
- python-3.x - Python - 熊猫 - 仅将数字单元格除以标量
- python - 使用 Django All Auth 时 /accounts/signup/ 'sociallogin' 处的 KeyError
- php - 选择后显示图像:function(event, ui)