我正在尝试创建一种方法,该方法将接收用户输入的任务和截止日期,并按截止日期对其进行排序。我有为任务编写的代码,它编译,但当我尝试排序它似乎删除所有内容。我在写原始文件吗?如何更正此内容以将其添加到同一文件而不删除?
public class DueDate implements Comparable<DueDate>{
public String addedTask = "";
public String dueDate = "";
public DueDate(String addedTask, String dueDate){
this.addedTask = addedTask;
this.dueDate = dueDate;
}
public String toString(){
return addedTask+"\t"+dueDate+"\t";
}
@Override
public int compareTo(DueDate o) {
return this.dueDate.compareTo(o.dueDate);
}
}
public class Main {
public static String fileName = "/Users/eri/Desktop/tasklistjava/src/javatask.txt";
public static void main(String[] args) throws IOException {
int menuItem = -1;
while(menuItem != 0){
menuItem = menu();
switch (menuItem){
case 1:
showTaskList();
break;
case 2:
addTask();
break;
case 3:
sortList();
case 4:
deleteTasks();
break;
case 0:
break;
default:
System.out.println("Invalid Input");
}
}
}
static void sortList() throws IOException {
System.out.println("\nSorted List\n");
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
ArrayList<DueDate> tasks = new ArrayList<DueDate>();
String line = "";
while((line = br.readLine()) != null) {
String[] values = line.split("-");
if(values.length == 2) {
String addedTask = values[0];
String dueDate = values[1];
DueDate d = new DueDate(addedTask, dueDate);
tasks.add(d);
}
}
Collections.sort(tasks);
for(int i = 0; i < tasks.size(); i++){
DueDate date = tasks.get(i);
String lineText = date.toString();
bw.write(lineText);
bw.newLine();
}
br.close();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
答案 0 :(得分:1)
通常,当您想要对文件中的记录进行排序时,您首先要取出内容并将其存储在arraylist中,然后在arraylist中对其进行排序。然后删除旧文件并将已排序的数据写入新文件。