Reputation: 1291
I have used below code to write something to my file google cloud storage.
FileService fileService = FileServiceFactory.getFileService();
GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
.setBucket(BUCKETNAME)
.setKey(FILENAME)
.setMimeType("text/html")
.setAcl("public_read")
.addUserMetadata("myfield1", "my field value");
AppEngineFile writableFile =
fileService.createNewGSFile(optionsBuilder.build());
// Open a channel to write to it
boolean lock = false;
FileWriteChannel writeChannel =
fileService.openWriteChannel(writableFile, lock);
// Different standard Java ways of writing to the channel
// are possible. Here we use a PrintWriter:
PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel, "UTF8"));
out.println("The woods are lovely dark and deep.");
out.println("But I have promises to keep.");
// Close without finalizing and save the file path for writing later
out.close();
String path = writableFile.getFullPath();
// Write more to the file in a separate request:
writableFile = new AppEngineFile(path);
// Lock the file because we intend to finalize it and
// no one else should be able to edit it
lock = true;
writeChannel = fileService.openWriteChannel(writableFile, lock);
// This time we write to the channel directly
writeChannel.write(ByteBuffer.wrap
("And miles to go before I sleep.".getBytes()));
// Now finalize
writeChannel.closeFinally();
resp.getWriter().println("Done writing...");
// At this point, the file is visible in App Engine as:
// "/gs/BUCKETNAME/FILENAME"
// and to anybody on the Internet through Cloud Storage as:
// (http://storage.googleapis.com/BUCKETNAME/FILENAME)
// We can now read the file through the API:
String filename = "/gs/" + BUCKETNAME + "/" + FILENAME;
AppEngineFile readableFile = new AppEngineFile(filename);
FileReadChannel readChannel =
fileService.openReadChannel(readableFile, false);
// Again, different standard Java ways of reading from the channel.
BufferedReader reader =
new BufferedReader(Channels.newReader(readChannel, "UTF8"));
String line = reader.readLine();
resp.getWriter().println("READ:" + line);
// line = "The woods are lovely, dark, and deep."
readChannel.close();
It seems it's writing and then reading, but when I check in the cloud storage area (using firefox), the file hasn't been edited. Any idea?
Upvotes: 0
Views: 1455
Reputation: 7054
Is this in the production or development environment?
When you're using the dev server writes to Google Storage are simulate and are not written to a real bucket.
Upvotes: 2
Reputation: 650
There could be two problems.
You could forget to add permissions to your bucket. Check https://developers.google.com/appengine/docs/java/googlestorage/overview#Prerequisites how to do it.
You are trying to update the file. After writeChannel.closeFinally() the file becomes read-only. You can not change/update/append to it.
Upvotes: 1