簡體   English   中英

寫入EC2上的文件

[英]Write to a file located on EC2

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

@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();
}

我這樣做錯了嗎? 文件位置是否錯誤? (程序運行無錯誤,但未顯示文件)。 任何幫助將不勝感激。

這就是我編寫該代碼的方式:

@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實例中執行,而不是遠程執行。

暫無
暫無

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

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