我在 Google App Engine 平台上的 JSF 中的程序出现问题。当我读到 GAE 不支持类 FileOutputStream 时,我几乎完成了在 Java EE 中实现聊天应用程序。 通过这个类对象,我创建文件,在其中写入聊天消息,并通过脚本加载该文件并在index.xhtml网站上刷新。
我需要帮助,因为我不知道可以替换哪个类来完成此应用程序FileOutputStream。我发现example in Python所以我知道这是可能的,但是如何在Java中实现它?
如果有任何帮助,我将不胜感激。
下面我使用 FileOutputSream 操作粘贴了 ChatBean 类的片段:
@Stateful
@ApplicationScoped
@ManagedBean(name="Chat")
public class ChatBean {
private List<String> users = new ArrayList<String>();
private String newUser;
FileOutputStream chatHtmlBufferWriter;
public ChatBean () throws IOException {
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String chatHtmlPath = ctx.getRealPath("/") + "chat";
try {
this.chatHtmlBufferWriter = new FileOutputStream(chatHtmlPath);
this.chatHtmlBufferWriter.write("Start chatu ąęć. <br />".getBytes("UTF-8"));
} catch (IOException ex) {
this.chatHtmlBufferWriter.close();
throw ex;
}
users.add("Admin");
}
@PreDestroy
public void closeFileBuffor() throws Exception {
this.chatHtmlBufferWriter.close();
}
public String addMessage(String msg) throws IOException {
this.chatHtmlBufferWriter.write(msg.getBytes("UTF-8"));
FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
return "index";
}
...
}
index.xhtml 文件中的脚本:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var currPos = 0;
var loadChat = function() {
$("#chatForm\\:chatbox").load('chat');
currPos = $(".chat")[0].scrollHeight;
$(".chat").scrollTop(currPos);
}
var scrollChat = function() {
$("#chatForm\\:chatbox").load('chat');
$(".chat").scrollTop(currPos);
}
var currPos;
$(document).ready(function() {
$("#chatForm\\:chatbox").load('chat', function(){
loadChat();
});
var refreshId = setInterval(function() {
scrollChat();
}, 1000);
$.ajaxSetup({ cache: false });
$("#chatForm\\:chatbox").scroll(function() {
currPos = $(".chat").scrollTop();
});
});
</script>
最佳答案
基本上,您不能直接写入文件系统(尽管您可以读取)。
您将需要使用现有的 GAE 存储 API 之一,例如具有 File like API 的 blobstore。 。其他选项的详细信息请参见 Storing Data page .
但是,我不确定您的想法是否正确;您只想创建一个返回当前消息并由脚本调用的 GET 方法。这些消息根本不会被写入文件。首先,您可以将消息存储在内存中。我怀疑您链接到的教程也有同样的作用。
(更新:我最初说 FileOutputStream 在白名单中,但我正在查看 FilterOutputStream
。哎呀。)
关于GAE 上的 Java 聊天应用程序将消息写入文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12128847/