GAE-use-cloudstorage

GAE中使用CloudStorage中的資源可以省略一些認證動作,透過FileReadChannel即可快速的取得存取CloudStorage的方法,範例如下:

Step1: 首先,Library的部分需要import下面藍色部分

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.PrintWriter;

import java.nio.ByteBuffer;

import java.nio.channels.Channels;

import java.util.logging.Logger;


import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.google.appengine.api.files.AppEngineFile;

import com.google.appengine.api.files.FileReadChannel;

import com.google.appengine.api.files.FileService;

import com.google.appengine.api.files.FileServiceFactory;

import com.google.appengine.api.files.FileWriteChannel;

import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;

import com.google.appengine.api.files.LockException;



最後,透過FileReadChannel讀取指定的CloudStorage檔案

public void readFile(HttpServletRequest req, HttpServletResponse resp)

     throws FileNotFoundException, LockException, IOException {

 // Get the file service

 FileService fileService = FileServiceFactory.getFileService();

 boolean lockForRead = false;

 String filename = "/gs/mitac-cp300-eu/test.txt";

 AppEngineFile readableFile = new AppEngineFile(filename);

 FileReadChannel readChannel =

   fileService.openReadChannel(readableFile, lockForRead);


 // Read the file in whichever way you'd like

 BufferedReader reader =

   new BufferedReader(Channels.newReader(readChannel, "UTF8"));

 String line = "";

 int i = 0;

 while((line = reader.readLine()) != null){

   resp.getWriter().println(i + ": " + line);

   i++;

 }


 readChannel.close();

}





附註:
依目前API release的狀況來看,目前Google著手進行大規模的API Refactory,看起來將會讓所有的API遵循使用RESTful的呼叫方式,因此API終會實作Credential的認證流程,本範例1.8.9版本以前測試均可以正常執行。

Comments