java - maven打包導(dǎo)致二進(jìn)制文件大小被改變
問題描述
使用class.getClassLoader().getResourceAsStream()這種方法獲取classpath下的文件流,讀取出來的文件比寫main方法讀出來的文件大小更大。
問題已經(jīng)解決。
本地main方法測試
使用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. 如何解決Centos下Docker服務(wù)啟動(dòng)無響應(yīng),且輸入docker命令無響應(yīng)?2. 我在centos容器里安裝docker,也就是在容器里安裝容器,報(bào)錯(cuò)了?3. 微信小程序session無法緩存的問題4. 怎么用 css3實(shí)現(xiàn)波浪底紋效果?5. vue.js - 關(guān)于Vue-cli項(xiàng)目在VPS中用Nginx部署完請(qǐng)求頁面app.js找不到提示404錯(cuò)誤。6. docker 17.03 怎么配置 registry mirror ?7. html - 這種錯(cuò)位的時(shí)間軸怎么布局,然后用css實(shí)現(xiàn)?8. 基于Nginx的Wordpress安裝失敗?9. css3 - 何時(shí)需要 flex-basis: 100% ?10. mysqld無法關(guān)閉
