在我的GWT項目(這是一款遊戲)中,我想將玩它的用戶的分數存儲到位於服務器端的文件中。並使用String在輸出中顯示它們。在GWT項目中寫入文本文件?
我可以從文件讀取數據,但是我無法寫入文件,它總是說Google App Engine不支持這個功能。 我想知道爲什麼Google App Engine不支持它? 有什麼辦法可以將數據添加到服務器端的文件? 請隨意添加您的所有意見,每一件事情將不勝感激。
在我的GWT項目(這是一款遊戲)中,我想將玩它的用戶的分數存儲到位於服務器端的文件中。並使用String在輸出中顯示它們。在GWT項目中寫入文本文件?
我可以從文件讀取數據,但是我無法寫入文件,它總是說Google App Engine不支持這個功能。 我想知道爲什麼Google App Engine不支持它? 有什麼辦法可以將數據添加到服務器端的文件? 請隨意添加您的所有意見,每一件事情將不勝感激。
您無法在App Engine上寫入file
,但您有兩個其他選項。
首先,如果您的文本低於1MB,則可以使用Text entity將文本存儲在數據存儲中。
其次,您可以將文字保存在Blobstore中。
用於文本文件寫入的代碼或依賴jar文件可以在GWT項目中使用,但執行cmd命令的代碼可以。
使用這樣的技巧來規避問題。下載commons-codec-1.10並添加到構建路徑。添加下面的代碼片段,可以在網上被複制到CMDUtils.java,放在了「共享」包:相應ABCService.java和ABCServiceAsync.java然後
public static StringBuilder execute(String... commands) {
StringBuilder result = new StringBuilder();
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(new String[] { "cmd" });
// put a BufferedReader
InputStream inputstream = proc.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
PrintWriter stdin = new PrintWriter(proc.getOutputStream());
for (String command : commands) {
stdin.println(command);
}
stdin.close();
// MUST read the output even though we don't want to print it,
// else waitFor() may fail.
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
result.append('\n');
}
} catch (IOException e) {
System.err.println(e);
}
return result;
}
添加補充:
public class ABCServiceImpl extends RemoteServiceServlet implements ABCService {
public String sendText(String text) throws IllegalArgumentException {
text= Base64.encodeBase64String(text.getBytes());
final String command = "java -Dfile.encoding=UTF8 -jar \"D:\\abc.jar\" " + text;
CMDUtils.execute(command);
return "";
}
而且abc.jar被創建爲在入口點包含這樣的主要方法可執行的JAR:
public static final String TEXT_PATH = "D:\\texts-from-user.txt";
public static void main(String[] args) throws IOException {
String text = args[0];
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(TEXT_PATH, true));
text = new String(Base64.decodeBase64(text));
writer.write("\n" + text);
writer.close();
}
我已經嘗試這樣做,它成功地適用於文本文件寫入的GWT p roject。
我確定我的文件不會超過1MB,它有10對(String name,int score)。那麼你更喜歡哪一個對我有用? 你會提供一些樣品嗎? – Dipak
滿足您的需求:這些選項都不是。您可以將它們保存爲10個獨立的實體,或者一個具有String屬性的實體。您應該閱讀如何在App Engine上存儲數據:https://developers.google.com/appengine/docs/java/datastore/overview –
我更喜歡一個帶有數組或列表字符串的實體。 – Dipak