1

现在我正在使用 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));
4

1 回答 1

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, ...);
于 2010-11-01T16:06:05.297 回答