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
問題解答
回答1:問題已經解決~!總結由于將一個二進制的文件放在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下文件的其他方法
相關文章:
1. python - 獲取到的數據生成新的mysql表2. javascript - js 對中文進行MD5加密和python結果不一樣。3. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現 4046. python - (初學者)代碼運行不起來,求指導,謝謝!7. 為啥不用HBuilder?8. python - flask sqlalchemy signals 無法觸發9. python的文件讀寫問題?10. 為什么python中實例檢查推薦使用isinstance而不是type?
