0

如何从 Java 中的输入流中读取多个 XML 文件并将它们写入 XML 文件?

我有这个:

InputStream is = new GZIPInputStream(new FileInputStream(file));

编辑:我有一个 tar.gz 文件,比如 xmls.tar.gz,它是包含多个 XML 文件的“文件”。当我使用以下方法将其转换为字符串时:

public static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

我把所有的 XML 文件和文件信息链接在一起。我System.out.println得到(这只是一个文件的开头):

blah.xml    60      0      0        2300 12077203627  10436 0ustar     0      0 <?xml version="1.0"...

回答:

这对我很有用,遵循 Keith 使用 Apache Compress 和 io 的建议:

http://thinktibits.blogspot.com/2013/01/read-extract-tar-file-java-example.html

import java.io.*;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.IOUtils;
public class unTar {  
        public static void main(String[] args) throws Exception{
                /* Read TAR File into TarArchiveInputStream */
                TarArchiveInputStream myTarFile=new TarArchiveInputStream(new FileInputStream(new File("tar_ball.tar")));
                /* To read individual TAR file */
                TarArchiveEntry entry = null;
                String individualFiles;
                int offset;
                FileOutputStream outputFile=null;
                /* Create a loop to read every single entry in TAR file */
                while ((entry = myTarFile.getNextTarEntry()) != null) {
                        /* Get the name of the file */
                        individualFiles = entry.getName();
                        /* Get Size of the file and create a byte array for the size */
                        byte[] content = new byte[(int) entry.getSize()];
                        offset=0;
                        /* Some SOP statements to check progress */
                        System.out.println("File Name in TAR File is: " + individualFiles);
                        System.out.println("Size of the File is: " + entry.getSize());                  
                        System.out.println("Byte Array length: " + content.length);
                        /* Read file from the archive into byte array */
                        myTarFile.read(content, offset, content.length - offset);
                        /* Define OutputStream for writing the file */
                        outputFile=new FileOutputStream(new File(individualFiles));
                        /* Use IOUtiles to write content of byte array to physical file */
                        IOUtils.write(content,outputFile);              
                        /* Close Output Stream */
                        outputFile.close();
                }               
                /* Close TarAchiveInputStream */
                myTarFile.close();
        }
}
4

1 回答 1

2

解压缩 (gzip) 后,您仍然需要解压缩。java JDK 没有用于 tar 的内置 API,但有几个可从第三方获得。请参阅此答案: 如何在 Java 中提取 tar 文件?

于 2013-07-17T13:06:39.227 回答