首頁  >  問答  >  主體

java - maven打包导致二进制文件大小被改变

使用class.getClassLoader().getResourceAsStream()这种方法获取classpath下的文件流,读取出来的文件比写main方法读出来的文件大小更大。

问题已经解决。

本地main方法测试

使用tomcat做为容器运行同样代码时

相关代码:

 synchronized (PhoneNumberGeo.class) {
        if (dataByteArray == null) {
          ByteArrayOutputStream byteData = new ByteArrayOutputStream();
          byte[] buffer = new byte[1024];

          int readBytesLength;
          try {
            InputStream inputStream = PhoneNumberGeo.class.getClassLoader()
                    .getResourceAsStream("phone.dat");
              while ((readBytesLength = inputStream.read(buffer)) != -1) {
              byteData.write(buffer, 0, readBytesLength);
            }
            inputStream.close();
          } catch (Exception e) {
            System.err.println("Can't find phone.dat in classpath phone.dat");
            e.printStackTrace();
            throw new RuntimeException(e);
          }

          dataByteArray = byteData.toByteArray();
        }
      }
    }

    byteBuffer = ByteBuffer.wrap(dataByteArray);
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    int dataVersion = byteBuffer.getInt();
    indexAreaOffset = byteBuffer.getInt();

完整代码:
开源代码github

伊谢尔伦伊谢尔伦2744 天前935

全部回覆(1)我來回復

  • 黄舟

    黄舟2017-04-18 10:49:12

    問題已經解決~!
    總結由於將一個二進位的檔案放在classpath下並且使用了maven-resources-plugin這個插件來拷貝資源檔案導致。

    詳細來說是應為maven-resources-plugin這個插件有一個選項

      <filtering>true</filtering>

    如果開啟那麼只要是classpath下要被拷貝的檔案預設都會被替換也就是說將會對應成properties
    之後就可以在xml的設定中使用,例如那個jdbc.properties。但這一個操作對於二進位文件,例如png,gif,pdf等就不合適了。
    我們需要將這些文件格式都排除掉。

    <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.4.3</version>
                    <configuration>
                        <encoding>UTF-8</encoding>
                        <nonFilteredFileExtensions>
                            <nonFilteredFileExtension>dat</nonFilteredFileExtension>
                            <nonFilteredFileExtension>swf</nonFilteredFileExtension>
                        </nonFilteredFileExtensions>
                    </configuration>
                </plugin>

    思考過程:
    開始走了不少彎路,我以為是因為專案的引用jar包問題,結果查詢了很久還是找不到原因。最後我把各個檔案的md5求出來才發現在target目錄下的檔案和resources目錄下的不一致,最後發現問題所在。

    參考:
    Maven Binary filtering
    取得classpath下檔案的其他方法

    回覆
    0
  • 取消回覆