簡體   English   中英

無法修改REST Web服務中的文本文件

[英]Unable to modify a text file in a REST Web service

我的程序實現了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,state)方法如下:

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好 但是文件行沒有更改。 問題出在哪兒?

提前致謝。

問題是您沒有指定完整的文件路徑。 因為您僅指定文件名,所以應用程序在當前目錄中搜索文件。 當您調用REST API方法時,當前目錄不是該文件所在的目錄,並且該方法找不到該文件。

您可以通過將完整路徑名指定為FileInputStreamFileOutputStream的參數來解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM