I am writing a program that a client will call POST method passing a string, inside the POST method, it will write the string to a file that located on EC2. But I am got stuck creating a file on EC2 and writing the content to it. So far I have a POST method like this:
@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();
}
Am I doing it wrong this way? Is the file location wrong? (The program runs without error, but no file presented). Any help will be greatly appreciated.
This is how I would write that code:
@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();
}
Things to consider:
/my-instance-public-ip-address/Desktop/
is an absolute path, the folder should exist and the java application needs to have permissions over it (eg if you are using tomcat, check that the tomcat user has permissions). This path is formatted to work on linux. Desktop
folder inside of it. /home/ubuntu/Desktop
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.