java - maven打包導(dǎo)致二進(jìn)制文件大小被改變
問題描述
使用class.getClassLoader().getResourceAsStream()這種方法獲取classpath下的文件流,讀取出來的文件比寫main方法讀出來的文件大小更大。
問題已經(jīng)解決。
本地main方法測(cè)試
使用tomcat做為容器運(yùn)行同樣代碼時(shí)
相關(guān)代碼:
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:問題已經(jīng)解決~!總結(jié)由于將一個(gè)二進(jìn)制的文件放在classpath下并且使用了maven-resources-plugin這個(gè)插件來拷貝資源文件導(dǎo)致。
詳細(xì)來說是應(yīng)為maven-resources-plugin這個(gè)插件有一個(gè)選項(xiàng)
<filtering>true</filtering>
如果開啟那么只要是classpath下要被拷貝的文件默認(rèn)都會(huì)進(jìn)行替換也就是說將會(huì)映射成properties之后就可以在xml的配置中使用,比如那個(gè)jdbc.properties。但是這一個(gè)操作對(duì)于二進(jìn)制文件,例如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>
思考過程:開始走了不少彎路,我以為是因?yàn)轫?xiàng)目的引用jar包問題,結(jié)果查詢了很久還是找不到原因。最后我把各個(gè)文件的md5求出來才發(fā)現(xiàn)在target目錄下的文件和resources目錄下的不一致,最終發(fā)現(xiàn)問題所在。
參考:Maven Binary filtering獲取classpath下文件的其他方法
相關(guān)文章:
1. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.2. 為什么我ping不通我的docker容器呢???3. android - webview 自定義加載進(jìn)度條4. mysql - 怎么讓 SELECT 1+null 等于 15. javascript - 微信音樂分享6. python - Django如何實(shí)現(xiàn)如下的參數(shù)為空的動(dòng)態(tài)查詢7. javascript - 微信小程序封裝定位問題(封裝異步并可能多次請(qǐng)求)8. 并發(fā)模型 - python將進(jìn)程池放在裝飾器里為什么不生效也沒報(bào)錯(cuò)9. linux - openSUSE 上,如何使用 QQ?10. python 怎樣用pickle保存類的實(shí)例?
