无法修改REST Web服务中的文本文件

时间:2019-04-24 15:40:39

标签: java rest

我的程序实现了REST Web服务的方法X,该方法在另一个类中调用另一个方法Y。后者修改文本文件中的一行。

我已经在不使用REST方法X的情况下测试了方法Y,并且一切顺利,并且文件已更改。但是当我调用PUT方法X时,文件没有更改。

Web服务的Java方法如下:

public String reduceEnergyConsumption(int id, String action) {
        String ch;
        int nb;
        if (action=="reduce")
            AQSensor.setState(id,"Off"); 
        else
            AQSensor.setState(id,"On");

        return action;
}

AQSensor是:

static AirQualitySensorManager AQSensor= new AirQualitySensorManagerImp();

setSate(id,状态)方法如下:

public void setState(int id, String state) {
        Vector<String> VInter= new Vector<String>();
        try {
            InputStream ips = new FileInputStream("stateAQS.txt");
            InputStreamReader ipsr = new InputStreamReader(ips);
            BufferedReader br = new BufferedReader(ipsr);
            String ligne;
            int i=0;
            while ((ligne = br.readLine()) != null)
            {
                i++;   
                VInter.add(ligne);
            }
            VInter.setElementAt(state, id);
    //****move the vector in the file
            OutputStream ops = new FileOutputStream("stateAQS.txt");
            OutputStreamWriter opsw = new OutputStreamWriter(ops);
            BufferedWriter bw = new BufferedWriter(opsw);
            for(int e=0;e<VInter.size();e++){
                bw.append(VInter.elementAt(e));
                bw.newLine();
            }
            bw.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

客户端中的调用代码如下:

Scanner sc = new Scanner(System.in);
System.out.println("enter the action: ");
String action = sc.nextLine();
System.out.println("enter the index: ");
String pr= sc.nextLine();

Entity<String> userEntity = Entity.entity(action, MediaType.TEXT_PLAIN);
Response response = target.path("aqsensor").path("reduceEnergy/"+pr+"/"+action).request().put(userEntity);

System.out.println("response is: "+response.getStatus());

现在,当我运行它时,它显示以下内容:

enter the action:
rise
enter the index:
5
response is: 200

那么200好。但是文件行没有更改。问题出在哪里?

谢谢。

1 个答案:

答案 0 :(得分:1)

问题是您没有指定完整的文件路径。因为您仅指定文件名,所以应用程序在当前目录中搜索文件。当您调用REST API方法时,当前目录不是该文件所在的目录,并且该方法找不到该文件。

您可以通过将完整路径名指定为参数FileInputStreamFileOutputStream来解决问题。