1 回答

TA贡献1830条经验 获得超9个赞
正如您已经提到的,您应该在保存之前转义新行字符,因为它们会破坏您的 csv 文件。
您可以使用description.replace("\n", "\\n")在保存description.replace("\\n", "\n")时转义和在加载时取消转义。
public void save() throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
for (Tasks o : (getTasks())) {
bw.write(o.getTask() + ";" +
o.getDeadline().toString() + ";" +
o.getDescription().replace("\n", "\\n"));
bw.newLine();
}
}
}
public void load() throws IOException, ParseException {
File file = new File(path);
if (file.exists()) {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
List<Tasks> tempTasks = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(";");
String task = parts[0];
LocalDate deadline = LocalDate.parse(parts[1]);
String desc = parts[2].replace("\\n", "\n");
tempTasks.add(new Tasks(task, deadline, desc));
}
tasks.clear();
tasks.addAll(tempTasks);
}
} else
tasks.clear();
}
但是;在你的标题或描述中使用 a 也会搞砸你的 csv。
我建议使用外部库来处理 csv,例如Apache Commons CSV。或者,您可以将任务保存为另一种文本格式,例如 json 或 xml。
添加回答
举报