使用TeeInputStream
复用InputStream
的读实现处理流的同时实现资源备份,区别于apache
的commons-io
中org.apache.commons.io.input.TeeInputStream
会存在如果处理资源未完成文件读取操作时导致剩余部分内容丢失的情况。
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class TeeInputStream extends InputStream {
private final InputStream inputStream;
private final OutputStream outputStream;
private byte[] bytes;
public TeeInputStream(InputStream inputStream, OutputStream outputStream) {
this.inputStream = inputStream;
this.outputStream = outputStream;
}
@Override
public long skip(long n) throws IOException {
if (n > 0 && bytes == null) {
bytes = new byte[1024];
}
long r = 0;
while (n > 0) {
int l = inputStream.read(bytes, 0, (int) (bytes.length > n ? n : bytes.length));
if (l > 0) {
outputStream.write(bytes, 0, l);
} else {
break;
}
r += l;
n -= l;
}
return r;
}
@Override
public int read(byte[] b) throws IOException {
int size = inputStream.read(b);
if (size > 0) {
outputStream.write(b, 0, size);
}
return size;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int size = inputStream.read(b, off, len);
if (size > 0) {
outputStream.write(b, off, size);
}
return size;
}
@Override
public int read() throws IOException {
int b = inputStream.read();
if (b != -1) {
outputStream.write(b);
}
return b;
}
@Override
public void close() throws IOException {
if (inputStream.available() > 0) {
int l;
if (bytes == null) {
bytes = new byte[1024];
}
while ((l = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, l);
}
}
inputStream.close();
}
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("test.xlsx");
OutputStream outputStream = new FileOutputStream("upload.xlsx");
InputStream teeInputStream = new TeeInputStream(inputStream, outputStream);
Workbook workbook = new XSSFWorkbook(teeInputStream);
Sheet sheet = workbook.getSheetAt(0);
int start = sheet.getFirstRowNum();
int end = sheet.getLastRowNum();
while (start <= end) {
Row row = sheet.getRow(start);
System.out.println("[" + start + "]" + row.getCell(0).getStringCellValue());
start++;
}
outputStream.close();
}
}