如何将ZipInputStream读入CharArrayReader

时间:2010-11-01 15:44:49

标签: google-app-engine zipinputstream

目前我正在使用Google App Engine(GAE)开发应用程序。 GAE不允许我为我创建临时文件夹来存储我的zip文件并从中读取。唯一的方法是从内存中读取它。 zipfile包含6个CSV文件,我需要将其读入CSVReader。

//part of the code

MultipartFormDataRequest multiPartRequest = null;

Hashtable files = multiPartRequest.getFiles();

UploadFile userFile = (UploadFile)files.get("bootstrap_file");

InputStream input = userFile.getInpuStream();

ZipInputStream zin = new ZipInputStream(input);

如何将ZipInputStream读入char [],这是为我的CSVReader对象创建CharArrayReader所必需的。

CSVReader reader = new CSVReader(CharArrayRead(char[] buf));

1 个答案:

答案 0 :(得分:3)

使用InputStreamReader包装ZipInputStream以从字节转换为字符;然后调用inputStreamReader.read(char [] buf,int offset,int length)来填充你的char []缓冲区,如下所示:

//part of the code
MultipartFormDataRequest multiPartRequest = null;
Hashtable files = multiPartRequest.getFiles();
UploadFile userFile = (UploadFile)files.get("bootstrap_file");
InputStream input = userFile.getInpuStream();
ZipInputStream zin = new ZipInputStream(input);

// wrap the ZipInputStream with an InputStreamReader    
InputStreamReader isr = new InputStreamReader(zin);
ZipEntry ze;
// ZipEntry ze gives you access to the filename etc of the entry in the zipfile you are currently handling
while ((ze = zin.getNextEntry()) != null) {
    // create a buffer to hold the entire contents of this entry
    char[] buf = new char[(int)ze.getSize()];
    // read the contents into the buffer
    isr.read(buf);
    // feed the char[] to CSVReader
    CSVReader reader = new CSVReader(CharArrayRead(buf));
}

如果你的CharArrayRead实际上是一个java.io.CharArrayReader,那么就不需要将它加载到char []中,你最好使用这样的代码:

InputStreamReader isr = new InputStreamReader(zin);
BufferedReader br = new BufferedReader(isr);
ZipEntry ze;
while ((ze = zin.getNextEntry()) != null) {
    CSVReader reader = new CSVReader(br);
}

如果您只有一个压缩文件(尝试绕过1MB限制),那么这将有效:

InputStreamReader isr = new InputStreamReader(zin);
zip.getNextEntry();
CSVReader reader = new CSVReader(isr, ...);