Search code examples
javaxmlinputstreamwhitespacezipinputstream

Remove whitespaces from XML file read from a zip file


I'm reading in an XML file that's stored inside a zip file. I need to remove the whitespaces, but I nothing seems to work. Here's what I have, but trim() isn't doing anything.

        for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {

            ZipEntry entry = (ZipEntry) e.nextElement();
            InputStream inputStream = zip.getInputStream(entry);
            InputStreamReader inputStreamReader = InputStreamReader(inputStream);  
            char[] buffer = new char[1024];
            while (inputStreamReader.read(buffer, 0, buffer.length) != -1) {

                String str = new String(buffer);

                System.out.println(str.trim());
       }

Solution

  • trim() will remove any leading or trailing whitespace, but I don't think you can combine the trim command with the System.out.println. Will that capture the results of the trim command?

    Have you tried the following?

    String result = str.trim();
    System.out.println(result);
    

    If that doesn't work, what about using replaceAll()?

    String result = str.replaceAll(" ","");
    System.out.println(result);
    

    Or if its not a simple whitespace character, try something like this that removes more than one whitespace?

    String result = str.replaceAll("\\s+","");
    System.out.println(result);