>  Q&A  >  본문

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

伊谢尔伦伊谢尔伦2744일 전932

모든 응답(1)나는 대답할 것이다

  • 黄舟

    黄舟2017-04-18 10:49:12

    문제가 해결되었습니다~!
    요약: 클래스패스에 바이너리 파일을 배치하고 maven-resources-plugin 플러그인을 사용하여 리소스 파일을 복사함으로써 발생합니다.

    자세히 말하면 maven-resources-plugin 플러그인 옵션이 있어야 합니다

    으아아아

    켜면 클래스 경로에 복사될 모든 파일이 기본적으로 대체됩니다. 즉, 속성에 매핑되고
    jdbc.properties와 같은 xml 구성에서 사용할 수 있습니다. . 하지만 이 작업은 png, gif, pdf 등과 같은 바이너리 파일에는 적합하지 않습니다.
    이러한 파일 형식을 제외해야 합니다.

    으아아아

    사고 과정:
    처음에는 프로젝트에서 참조하는 jar 패키지 문제 때문인 줄 알았는데, 오랫동안 검색해도 이유를 찾을 수 없었습니다. . 마지막으로 각 파일의 md5를 알아내서 대상 디렉터리의 파일이 리소스 디렉터리의 파일과 일치하지 않는 것을 발견하고 마침내 문제를 발견했습니다.

    참고:
    Maven 바이너리 필터링
    클래스 경로에서 파일을 얻는 다른 방법

    회신하다
    0
  • 취소회신하다