[英]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上使用。 Desktop
文件夹。 /home/ubuntu/Desktop
具有Desktop文件夹。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.