1 回答

TA貢獻1942條經驗 獲得超3個贊
您應該在保存之前轉義新的行字符,因為它們會破壞您的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。
添加回答
舉報