How to extract the information of an xml file in a zip to a Java String

35 Views Asked by At

Right now I'm struggling with files, streams, buffers readers and writers.

So I have a zipFile who contains an XML file. My objective is to recover the information of the XML into a String.

Right now my code looks like that:

 byte[] buffer = new byte[2048];
        String outpath = "";

        // open the zip file stream
        try(InputStream theFile = new FileInputStream(TEST_ZIP);
        ZipInputStream stream = new ZipInputStream(theFile)){

            ZipEntry entry;
            while((entry = stream.getNextEntry())!=null) {

                // Once we get the entry from the stream, the stream is
                // positioned read to read the raw data, and we keep
                // reading until read returns 0 or less.
                outpath = DOSSIER + "/" + entry.getName();

                try (FileOutputStream output = new FileOutputStream(outpath)) {
                    int len = 0;
                    while ((len = stream.read(buffer)) > 0) {
                        output.write(buffer, 0, len);
                    }
                }
            }
        }

        var file = new File(outpath);
        String content = getContentFromFile(file);
        file.delete();

The method getCOntentFromFile is the following:

 private static String getContentFromFile(File file) {
        String content = new String();
        if (file.exists()) {
            try (FileReader fileReader = new FileReader(file);
                 BufferedReader bufferedReader = new BufferedReader(fileReader)) {
                String linea;
                while ((linea = bufferedReader.readLine()) != null) {
                    content = content + linea;
                }

            } catch (IOException e) {
                System.out.println("Erreur lors de la lecture du fichier." + e.getMessage());
            }
        } else {
            System.out.println("Le fichier n'existe pas.");
        }
        return content;
    }

The code is working but I'm wondering if there would be an easier/better way to do that extraction.

1

There are 1 best solutions below

0
VGR On

That seems like a lot of extra work. Your question implies that there is only one entry in the zip file, so you can just read that one entry directly:

byte[] bytes;
try (ZipFile zipFile = new ZipFile(TEST_ZIP);
     InputStream stream = zipFile.getInputStream(
        zipFile.stream().findFirst().orElseThrow())) {

    bytes = stream.readAllBytes();
}

String content = new String(bytes, StandardCharsets.UTF_8);

No need to write the bytes to a separate file.