同样的文件,在Tomcat和Resin环境下,读取的流居然不一样?

先上读取文件的代码:

  public static String getHexString(byte[] b) {
    String str = "";
    for (int i = 0; i < b.length; i ++) {
      String hex = Integer.toHexString(b[i] & 0xFF);
      if (hex.length() == 1)
        hex = '0' + hex;
      str += hex.toUpperCase();
    }
    return str;
  }

  public static final void getP() {
    InputStream bmpInput = null;
    try {
      Resource resource = new ClassPathResource("com/mww/action/test.bmp", Utils.class.getClassLoader());
      if (resource == null || ! resource.exists())
        return;

      System.out.println(resource.contentLength());
      System.out.println(resource.getDescription());
      System.out.println(resource.getFilename());
      System.out.println(resource.getURI().toString());
      System.out.println(resource.getURL().toString());

      StringBuilder sb = new StringBuilder();

      byte[] bytes = new byte[8];
      bmpInput = resource.getInputStream();

      while (bmpInput.read(bytes) != - 1)
        sb.append(getHexString(bytes));

      FileUtils.writeStringToFile(new File("D:\\key.txt"), sb.toString());
    } catch (IOException e) {
      return;
    } finally {
      IOUtils.closeQuietly(bmpInput);
    }
  }

 其中打印resource信息部分,输出的内容完全一样,包括文件长度:

-- Tomcat
25014
class path resource [com/mww/action/test.bmp]
test.bmp
jar:file:/D:/wwwroot/WEB-INF/lib/webapp.jar!/com/mww/action/test.bmp
jar:file:/D:/wwwroot/WEB-INF/lib/webapp.jar!/com/mww/action/test.bmp

-- Resin
25014
class path resource [com/mww/action/test.bmp]
test.bmp
jar:file:/D:/wwwroot/WEB-INF/lib/webapp.jar!/com/mww/action/test.bmp
jar:file:/D:/wwwroot/WEB-INF/lib/webapp.jar!/com/mww/action/test.bmp

 

但是,输出的key.txt文件内容居然不一样!!Resin比Tomcat在文件的中间和结尾多出了8个字节。。。如下图:


 

这是咋子回事???

 

[color=darkblue][b]
while (bmpInput.read(bytes) != - 1)

sb.append(getHexString(bytes));

这一段有问题哦
bmpInput.read(bytes)返回的是读入字节的长度, 有可能是0 !

而且你getHexString(bytes), 按你的程序, bytes数组里面不一定是全部读取出来的哦[/b][/color]