下面的代码出自struts2的示例,但是其中已经有个StringBufferInputStream类已经过时了,怎么办?
http://struts.apache.org/2.x/docs/ajax.html
Both Struts 1 and Struts 2 can return any type of response. We are not limited to forwarding to a server page. In Struts 1, you can just do something like:
response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("Hello World! This is an AJAX response from a Struts Action.");out.flush();return null;
In Struts 2, we can do the same thing with a Stream result.
Struts 2 Stream result Action package actions;import java.io.InputStream;import java.io.StringBufferInputStream;import com.opensymphony.xwork2.ActionSupport;public class TextResult extends ActionSupport { private InputStream inputStream; public InputStream getInputStream() { return inputStream; } public String execute() throws Exception { inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action."); return SUCCESS; }}
办法是这样的,用ByteArrayInputStream代替StringBufferInputStream,红色代码是新加的:
package actions; import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("deprecation")
public class TextResult extends ActionSupport {
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public String execute() throws Exception {
inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
String str = new String("中文stream");
inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
return SUCCESS;
}
}
还需要注意一个问题,为什么要用UTF-8,本人的源程序是GBK格式的,但是用str.getBytes("GBK")就是不行,字符串显示不出来。经过反复试验,基本认定是因为源程序要编译后才运行,编译后,里面的字符串存储的格式全部是unicode了。所以需要用UTF-8。
假如程序运行后,还要从外部读入文件,那个时候,这个文件是什么字符集的,就需要按实际情况匹配了。