GWT项目中不能使用写文本文件的代码或依赖jar文件,但是执行cmd命令的代码可以。
使用这样的技巧来规避问题。下载 commons-codec-1.10 并添加到构建路径。将以下可以在线复制的 sn-p 添加到 CMDUtils.java 并放入 'shared' 包中:
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 被创建为一个可执行的 jar,其中入口点包含这样的 main 方法:
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 项目的文本文件写入工作。