2017-10-14 34 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