2017-10-14 33 views
0

我正在編寫一個程序,客戶端將調用POST方法傳遞一個字符串,在POST方法內,它會將該字符串寫入位於EC2上的文件。但我被困在EC2上創建一個文件並將內容寫入它。到目前爲止,我有一個像這樣的POST方法:寫入位於EC2上的文件

@POST 
@Path("/post") 
@Consumes(MediaType.APPLICATION_XML) 
@Produces(MediaType.APPLICATION_XML) 
public Response postEntry(MyEntry myEntry) throws URISyntaxException { 
    try { 
     FileWriter fw = new FileWriter("\\\\my-instance-public-ip-address\\Desktop\\data.txt", true); 
     BufferedWriter bw = new BufferedWriter(fw); 
     bw.write(myEntry.toString()); 
     bw.close(); 
     fw.close(); 

    } catch (Exception e) { 
     System.err.println("Failed to insert : " + e.getCause()); 
     e.printStackTrace(); 
    } 
    String result = "Entry written: " + myEntry.toString(); 
    return Response.status(201).entity(result).build(); 
} 

我做錯了嗎?文件位置是否錯誤? (該程序運行時沒有錯誤,但沒有提交文件)。任何幫助將不勝感激。

+0

爲什麼你沒有在操作系統中用EC2 Instance標記你的問題? – 2017-10-14 23:36:32

回答

0

這是我會怎麼寫代碼:

@POST 
@Path("/post") 
@Consumes(MediaType.APPLICATION_XML) 
@Produces(MediaType.APPLICATION_XML) 
public Response postEntry(MyEntry myEntry) throws URISyntaxException { 

    String filename = "/my-instance-public-ip-address/Desktop/data.txt"; 

    // use try-with-resources (java 7+) 
    // if the writters are not closed the file may not be written 
    try (FileWriter fw = new FileWriter(filename, true); 
      BufferedWriter bw = new BufferedWriter(fw)){ 

     bw.write(myEntry.toString()); 

    } catch (Exception e) { 

     String error = "Failed to insert : " + e.getCause(); 

     // Use a logger 
     // log.error("Failed to insert entry", e); 

     // don't print to the console 
     System.err.println(error); 
     // never use printStackTrace 
     e.printStackTrace(); 

     // If there is an error send the right status code and message 
     return Response.status(500).entity(error).build(); 
    } 

    String result = "Entry written: " + myEntry.toString(); 
    return Response.status(201).entity(result).build(); 
} 

需要考慮的事情:

  • /my-instance-public-ip-address/Desktop/是絕對路徑,該文件夾應該存在和Java應用程序需要有超過它的權限(例如,如果您使用的是tomcat,請檢查tomcat用戶是否有權限)。該路徑被格式化爲在Linux上工作。
  • 我不知道爲什麼在文件系統的根目錄中有一個公共IP地址的文件夾,或者爲什麼它裏面有一個Desktop文件夾。
  • 在EC2中,Ubuntu機器通常有/home/ubuntu/Desktop中的Desktop文件夾。
  • 代碼應該在EC2實例中執行,而不是遠程執行。
+0

謝謝。是的。也嘗試過。不起作用.. – potbelly

+0

您是否嘗試添加磁盤標籤'D:\\ my-instance-ip-address \\ Desktop \\ data.txt'(是否爲windows?) –

+0

不是窗口。它是AWS – potbelly