java - maven打包導(dǎo)致二進(jìn)制文件大小被改變
問(wèn)題描述
使用class.getClassLoader().getResourceAsStream()這種方法獲取classpath下的文件流,讀取出來(lái)的文件比寫main方法讀出來(lái)的文件大小更大。
問(wèn)題已經(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();
完整代碼:開(kāi)源代碼github
問(wèn)題解答
回答1:問(wèn)題已經(jīng)解決~!總結(jié)由于將一個(gè)二進(jìn)制的文件放在classpath下并且使用了maven-resources-plugin這個(gè)插件來(lái)拷貝資源文件導(dǎo)致。
詳細(xì)來(lái)說(shuō)是應(yīng)為maven-resources-plugin這個(gè)插件有一個(gè)選項(xiàng)
<filtering>true</filtering>
如果開(kāi)啟那么只要是classpath下要被拷貝的文件默認(rèn)都會(huì)進(jìn)行替換也就是說(shuō)將會(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>
思考過(guò)程:開(kāi)始走了不少?gòu)澛罚乙詾槭且驗(yàn)轫?xiàng)目的引用jar包問(wèn)題,結(jié)果查詢了很久還是找不到原因。最后我把各個(gè)文件的md5求出來(lái)才發(fā)現(xiàn)在target目錄下的文件和resources目錄下的不一致,最終發(fā)現(xiàn)問(wèn)題所在。
參考:Maven Binary filtering獲取classpath下文件的其他方法
相關(guān)文章:
1. 一個(gè)走錯(cuò)路的23歲傻小子的提問(wèn)2. angular.js - angularjs 使用鼠標(biāo)懸停時(shí),標(biāo)簽一直閃3. 我在centos容器里安裝docker,也就是在容器里安裝容器,報(bào)錯(cuò)了?4. 在mac下出現(xiàn)了兩個(gè)docker環(huán)境5. angular.js - angularjs的自定義過(guò)濾器如何給文字加顏色?6. c++ - win764位環(huán)境下,我用GCC為什么指針占8個(gè)字節(jié),而long是4個(gè)字節(jié)?7. java - Hibernate查詢的數(shù)據(jù)是存放在session中嗎?8. python 計(jì)算兩個(gè)時(shí)間相差的分鐘數(shù),超過(guò)一天時(shí)計(jì)算不對(duì)9. html5 - HTML代碼中的文字亂碼是怎么回事?10. python - django 里自定義的 login 方法,如何使用 login_required()
