GWTプロジェクトでは、テキストファイル書き込み用のコードまたは依存jarファイルを使用できませんが、cmdコマンドを実行するためのコードは使用できます。
このようなトリックを使用して、問題を回避します。commons -codec-1.10をダウンロードし、ビルドパスに追加します。オンラインでCMDUtils.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;
}
対応するABCService.javaとABCServiceAsync.javaを追加してから、以下を追加します。
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は、エントリポイントに次のようなmainメソッドが含まれる実行可能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プロジェクトのテキストファイルの書き込みに正常に機能します。