0

I need to convert a PHP code to Java. One of the functions converts a zip file to a URL-encoded format. I use the same zipped folder (containing a .csv file in it).

In PHP using this code, I get this response

$file = "batch.zip";
echo file_get_contents($file);

Response: PK �mSRbatch/PKjRR_I��75*batch/batch_2020-08-31-14-43-09 - Copy.csv�M-.NLO�)��I+���I�O��K��JIK)N+N�1107��4�446�1�����5��PK �mSR$batch/ V*u��V*u��C~1p��PKjRR_I��75*$ $batch/batch_2020-08-31-14-43-09 - Copy.csv S{�-���"�t�����s��PK��

But when I try to open the same file in Java (I am using Maven) I get this response

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream file = classloader.getResourceAsStream("batch.zip");
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader
  (file, Charset.forName(StandardCharsets.UTF_8.name())))) {
    int c = 0;
    while ((c = reader.read()) != -1) {
      textBuilder.append((char) c);
    }
}
System.out.println("textBuilder = " + textBuilder.toString());

Response: textBuilder = PK
     �mSR               batch/PK   jRR_I��7   5   *   batch/batch_2020-08-31-14-43-09 - Copy.csv�M-.NLO�)��I+���I�O��K��JIK)N+N�1107��4�446�1�����5�� PK 
     �mSR             $              batch/
         V*u��V*u��C~1p��PK    jRR_I��7   5   * $           $   batch/batch_2020-08-31-14-43-09 - Copy.csv
         S{�-���"�t�����s��PK      �   �     

Besides the many space that exists in the file read with Java, I get some missing characters too. Any help? My final goal is to read a zip file, encode it to base 64 and url encode it in the end

  • 1
    Use an InputStream, not a Reader. A zip file’s contents are not text. – VGR Feb 19 '21 at 13:01
  • … and the in addition, the zip file's zipped content is not UTF-8 (or whatever) encoded. Encoding comes into picture only for the unzipped contents. – tquadrat Feb 19 '21 at 13:08
  • How to do that in Java? I am pretty new. – bububeti07 Feb 19 '21 at 13:09
  • I solved it, I found this which helped me a lot. https://stackoverflow.com/questions/31848316/convert-zip-to-byte-array-without-saving-the-output-to-file – bububeti07 Feb 19 '21 at 13:35

0 Answers0