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>
思考過程:開始走了不少?gòu)澛罚乙詾槭且驗(yàn)轫?xiàng)目的引用jar包問題,結(jié)果查詢了很久還是找不到原因。最后我把各個(gè)文件的md5求出來才發(fā)現(xiàn)在target目錄下的文件和resources目錄下的不一致,最終發(fā)現(xiàn)問題所在。
參考:Maven Binary filtering獲取classpath下文件的其他方法
相關(guān)文章:
1. 為什么autoloader.php文件能知道 $className 代表test2. node.js - win7下,npm 無法下載依賴包,淘寶鏡像也裝不上,求幫忙???3. python - matplotlib安裝之后使用出錯(cuò)4. 為什么學(xué)習(xí)PHP5. javascript - js輸入框限定字?jǐn)?shù)問題6. pdo - mysql 簡(jiǎn)單注入疑問7. javascript - vue項(xiàng)目里的package.json8. android - 微信登陸不回調(diào)問題9. python - 關(guān)于爬取網(wǎng)站,下載圖片的時(shí)候碰到網(wǎng)址結(jié)構(gòu)問題卡住10. javascript - table固定尾行,有人寫過嗎?
