java.io.InputStream available()真是一个奇葩的方法啊

我要向数据库里面存头像图片,用了longblob字段,数据库是Mysql5.0
代码如下
PreparedStatement pstat=null;
			try {
				pstat = conn.prepareStatement(sql);
				String md5name=MD5Util.StringMD5(filename);
				pstat.setString(1, name);
				pstat.setString(2, md5name);
				pstat.setTimestamp(3, now);
				pstat.setTimestamp(4, now);
				pstat.setBinaryStream(5, inStream, inStream.available());//这一句老是报错,耽误了我一个下午
				pstat.executeUpdate();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new Exception("save img:"+name+" to database failed");
			}
开始以为是数据库的问题,然后想到可能是乱码的问题,Google了一个下午,最后偶然看了一下jdk的API文档
java.io.InputStream available()这个方法就是用来坑爹的。
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

文档里说,这个方法不保证返回数据的准确性,最后用Common-IO包的IOUtils.copyLarge这个方法解决了。
这个方法返回的长度应该是准确的,没报错了。

你可能感兴趣的:(common-io,java.io)