如何处理过时的StringBufferInputStream

本文介绍了如何在Struts2框架中替代已过时的StringBufferInputStream类,提供了使用ByteArrayInputStream的解决方案,并解释了为什么需要使用UTF-8编码以及源程序在编译后字符集转换为unicode的原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的代码出自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。

假如程序运行后,还要从外部读入文件,那个时候,这个文件是什么字符集的,就需要按实际情况匹配了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值