如何从txt.file中删除RESTful Java

时间:2016-01-10 08:23:13

标签: java

我是Java语言的新手,我尝试制作RESTful服务。我的DELETE功能有问题。删除值后,我尝试将新的arrayList保存在我的文件中。在我的控制台中,我要删除的值被删除,但在我的文件中,仍然是。

@GET
@Path("/arraylist")
public ArrayList<Student>displayJsonFile() throws IOException{  
    ArrayList<Student> students = new ArrayList<Student>();

    File jsonFile = new File("/students.txt");
    Scanner fileInput = new Scanner(jsonFile);
    Gson gson = new Gson();
    while (fileInput.hasNextLine()){    
        String jsonLine = fileInput.nextLine();

        Student singleStudent = gson.fromJson(jsonLine, Student.class);
        students.add(singleStudent);
    }
    fileInput.close();
    return students;    
}



@DELETE
@Path("/delUser/{id}/{name}/{yearOfBirth}") 

    public String delStudents(@PathParam("id") String id, @PathParam("name") String name,@PathParam("yearOfBirth") int yearOfBirth) throws IOException{ 

        Student delStudent = new Student();
        delStudent.setId(id);
        delStudent.setName(name);
        delStudent.setYearOfBirth(yearOfBirth);

        ArrayList<Student> studentss = new ArrayList<Student>();
        for(int j = 0 ; j<displayJsonFile().size(); j++){

            studentss.add(j, displayJsonFile().get(j)) ;

        }

        for(int i=0;i<displayJsonFile().size();i++){

            if(studentss.get(i).equals(delStudent)){
                studentss.remove(i);
                break;
            }
        }

        return "Student deleted !";

    }

1 个答案:

答案 0 :(得分:1)

您的DELETE方法中没有任何代码可以从文件中删除学生。

此代码段应该执行此操作。

@DELETE
@Path("/delUser/{id}/{name}/{yearOfBirth}") 

    public String delStudents(@PathParam("id") String id, @PathParam("name") String name,@PathParam("yearOfBirth") int yearOfBirth) throws IOException{ 

        Student delStudent = new Student();
        delStudent.setId(id);
        delStudent.setName(name);
        delStudent.setYearOfBirth(yearOfBirth);

        ArrayList<Student> studentss = new ArrayList<Student>();
        for(int j = 0 ; j<displayJsonFile().size(); j++){

            studentss.add(j, displayJsonFile().get(j)) ;

        }
        for(int i=0;i<displayJsonFile().size();i++){

            if(studentss.get(i).equals(delStudent)){
                studentss.remove(i);
                break;
            }
        }

        File oldJsonFile = new File("/students.txt");
        oldJsonFile.delete();
        File jsonFile = new File("/students.txt"); 
        FileWriter fw = new FileWriter(fnew, false);   
        for (Student student : studentss) {
             // Add a public String toJsonString method to your student 
             // class to convert your Student object to json
             // or use Gson's serializer and call it here to generate json
             fw.write(student.toJsonString());
        }
        fw.close();
        return "Student deleted !";

    }