有关inputstream流只能读取一次的问题

最近在学习servlete,无意中发现在以post方法提交表单信息后,在servlet端用getInputStream()接收实体信息后,再用getParameter()获取是,发现为null.我就十分困惑。代码如下

               //post获取实体信息    getinputstream

InputStream in = request.getInputStream();

int len = 0;
byte[] buf = new byte[1024];
while((len = in.read(buf)) != -1){
String str = new String(buf,0,len);
System.out.print(str);
}
System.out.println();
in.reset();
//getParameter()
String name = request.getParameter("username");
String psw = request.getParameter("psw");
System.out.println(name+","+psw);
System.out.println();


        后面在查询资料中发现 InputStream 只能获取一次情况。下面示例代码

               String str = "AAAAABBBBBCCCCDDDDEEEEEFFFFF";
File f = new File("D:\\test.txt");
OutputStream out = null;
InputStream in = null;
//将str写入test.txt
out = new FileOutputStream(f);
byte[] buf = str.getBytes();
out.write(buf);
out.close();

//将str读出
in = new FileInputStream(f);

byte[] a = new byte[5];
in.read(a);
System.out.println(new String(a,0,5));


int len = 0;
byte[] b = new byte[1024];
while((len = in.read(b)) != -1){
String str1 = new String(b,0,len);
System.out.print(str1);
}

       红色标记的代码就是主要测试代码,当去掉这一行时,正常输出为:AAAAABBBBBCCCCDDDDEEEEEFFFFF。
       当加上此行时,输出为: AAAAA
                                                    BBBBBCCCCDDDDEEEEEFFFFF
       此次 in输入流读了2次数,第一次读出5个字符,,第二次读出剩下的全部。
       那么问题来了,我查取了API的inputstream 中的read()方法 是这样解释的:
               
 public int read(byte[] b,int off, int len)
   Reads up to len bytes of data into an array of bytes from this input stream. If
pos equals count, then -1 is  returned to indicate     end of file. Otherwise, the number k of bytes read is equal to the smaller of len and count-pos.If k is positive, then bytes buf[pos] through buf[pos+k-1] are copied into b[off] through b[off+k-1] in the manner performed by System.arraycopy. The value k is added into pos and k is returned.
       在InputStream读取的时候,会有一个pos指针,它指示每次读取之后下一次要读取的起始位置。在每次读取后会更新pos的值,当你下次再来读取的时候是从pos的位置开始的,而不是从头开始,所以第二次获取String中的值的时候是不全的,API中提供了一个解决办法:reset()。但我发现在inputStream和servlet中根本不起作用。提示 mark/reset not supported 。意思是只有重写过markSupported()方法的IO流才可以用。所以一般我们使用inputStream,最好在一次内处理完所有逻辑。
      
       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值