提交 0a0d8a94 编写于 作者: Z zhuangjiaju

优化读写的写法,方便读写

上级 ce03b82c
......@@ -146,6 +146,9 @@
<ruleset>rulesets/java/ali-other.xml</ruleset>
<ruleset>rulesets/java/ali-set.xml</ruleset>
</rulesets>
<excludes>
<exclude>com/alibaba/excel/event/AnalysisEventListener.java</exclude>
</excludes>
</configuration>
<executions>
<!-- 绑定pmd:check到verify生命周期 -->
......
......@@ -11,8 +11,16 @@ import com.alibaba.excel.read.metadata.ReadSheet;
*/
public interface ExcelExecutor {
/**
* Returns the actual sheet in excel
*
* @return
*/
List<ReadSheet> sheetList();
/**
* Read sheet
*/
void execute();
}
package com.alibaba.excel.analysis.v03;
/**
*
* @author Dan Zheng
*/
public abstract class AbstractXlsRecordHandler implements XlsRecordHandler {
protected int row = -1;
protected int column = -1;
......
......@@ -2,12 +2,57 @@ package com.alibaba.excel.analysis.v03;
import org.apache.poi.hssf.record.Record;
/**
* Intercepts handle xls reads.
*
* @author Dan Zheng
*/
public interface XlsRecordHandler extends Comparable<XlsRecordHandler> {
/**
* Which tags are supported
*
* @param record
* @return
*/
boolean support(Record record);
/**
* Initialize
*/
void init();
/**
* Processing record
*
* @param record
*/
void processRecord(Record record);
/**
* Get row
*
* @return
*/
int getRow();
/**
* Get column
*
* @return
*/
int getColumn();
/**
* Get value
*
* @return
*/
String getValue();
/**
* Get order
*
* @return
*/
int getOrder();
}
......@@ -17,15 +17,15 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.analysis.v03.handlers.BOFRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.BlankOrErrorRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.BofRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.FormulaRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.LabelRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.MissingCellDummyRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.NoteRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.NumberRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.RKRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.SSTRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.RkRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.SstRecordHandler;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.read.listener.event.EachRowAnalysisFinishEvent;
......@@ -178,13 +178,13 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
private void buildXlsRecordHandlers() {
if (CollectionUtils.isEmpty(recordHandlers)) {
recordHandlers.add(new BlankOrErrorRecordHandler());
recordHandlers.add(new BOFRecordHandler(workbookBuildingListener, analysisContext, sheets));
recordHandlers.add(new BofRecordHandler(workbookBuildingListener, analysisContext, sheets));
recordHandlers.add(new FormulaRecordHandler(stubWorkbook, formatListener));
recordHandlers.add(new LabelRecordHandler());
recordHandlers.add(new NoteRecordHandler());
recordHandlers.add(new NumberRecordHandler(formatListener));
recordHandlers.add(new RKRecordHandler());
recordHandlers.add(new SSTRecordHandler());
recordHandlers.add(new RkRecordHandler());
recordHandlers.add(new SstRecordHandler());
recordHandlers.add(new MissingCellDummyRecordHandler());
Collections.sort(recordHandlers);
}
......
package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import org.apache.poi.hssf.record.*;
/**
* Record handler
*
* @author Dan Zheng
*/
public class BlankOrErrorRecordHandler extends AbstractXlsRecordHandler {
@Override
......
......@@ -12,16 +12,21 @@ import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.metadata.ReadSheet;
public class BOFRecordHandler extends AbstractXlsRecordHandler {
/**
* Record handler
*
* @author Dan Zheng
*/
public class BofRecordHandler extends AbstractXlsRecordHandler {
private List<BoundSheetRecord> boundSheetRecords = new ArrayList<BoundSheetRecord>();
private BoundSheetRecord[] orderedBSRs;
private BoundSheetRecord[] orderedBsrs;
private int sheetIndex;
private List<ReadSheet> sheets;
private AnalysisContext context;
private boolean analyAllSheet;
private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener;
public BOFRecordHandler(EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener,
public BofRecordHandler(EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener,
AnalysisContext context, List<ReadSheet> sheets) {
this.context = context;
this.workbookBuildingListener = workbookBuildingListener;
......@@ -40,11 +45,11 @@ public class BOFRecordHandler extends AbstractXlsRecordHandler {
} else if (record.getSid() == BOFRecord.sid) {
BOFRecord br = (BOFRecord)record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
if (orderedBsrs == null) {
orderedBsrs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
sheetIndex++;
ReadSheet readSheet = new ReadSheet(sheetIndex, orderedBSRs[sheetIndex - 1].getSheetname());
ReadSheet readSheet = new ReadSheet(sheetIndex, orderedBsrs[sheetIndex - 1].getSheetname());
sheets.add(readSheet);
if (this.analyAllSheet) {
context.currentSheet(null, readSheet);
......@@ -59,7 +64,7 @@ public class BOFRecordHandler extends AbstractXlsRecordHandler {
this.analyAllSheet = true;
}
sheetIndex = 0;
orderedBSRs = null;
orderedBsrs = null;
boundSheetRecords.clear();
sheets.clear();
}
......
package com.alibaba.excel.analysis.v03.handlers;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
/**
* Record handler
*
* @author Dan Zheng
*/
public class FormulaRecordHandler extends AbstractXlsRecordHandler {
private int nextRow;
private int nextColumn;
......@@ -16,10 +24,12 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler {
private boolean outputNextStringRecord;
private FormatTrackingHSSFListener formatListener;
private HSSFWorkbook stubWorkbook;
public FormulaRecordHandler(HSSFWorkbook stubWorkbook, FormatTrackingHSSFListener formatListener) {
this.stubWorkbook = stubWorkbook;
this.formatListener = formatListener;
}
@Override
public boolean support(Record record) {
return FormulaRecord.sid == record.getSid() || StringRecord.sid == record.getSid();
......
package com.alibaba.excel.analysis.v03.handlers;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
/**
* Record handler
*
* @author Dan Zheng
*/
public class LabelRecordHandler extends AbstractXlsRecordHandler {
@Override
public boolean support(Record record) {
......
package com.alibaba.excel.analysis.v03.handlers;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
/**
* Record handler
*
* @author Dan Zheng
*/
public class MissingCellDummyRecordHandler extends AbstractXlsRecordHandler {
@Override
public boolean support(Record record) {
......
package com.alibaba.excel.analysis.v03.handlers;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import org.apache.poi.hssf.record.NoteRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
/**
* Record handler
*
* @author Dan Zheng
*/
public class NoteRecordHandler extends AbstractXlsRecordHandler {
@Override
public boolean support(Record record) {
......@@ -16,7 +22,6 @@ public class NoteRecordHandler extends AbstractXlsRecordHandler {
this.row = nrec.getRow();
this.column = nrec.getColumn();
// TODO: Find object to match nrec.getShapeId()
this.value = "(TODO)";
}
......
package com.alibaba.excel.analysis.v03.handlers;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
/**
* Record handler
*
* @author Dan Zheng
*/
public class NumberRecordHandler extends AbstractXlsRecordHandler {
private FormatTrackingHSSFListener formatListener;
public NumberRecordHandler(FormatTrackingHSSFListener formatListener) {
this.formatListener = formatListener;
}
@Override
public boolean support(Record record) {
return NumberRecord.sid == record.getSid();
......
package com.alibaba.excel.analysis.v03.handlers;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import org.apache.poi.hssf.record.RKRecord;
import org.apache.poi.hssf.record.Record;
public class RKRecordHandler extends AbstractXlsRecordHandler {
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
/**
* Record handler
*
* @author Dan Zheng
*/
public class RkRecordHandler extends AbstractXlsRecordHandler {
@Override
public boolean support(Record record) {
return RKRecord.sid == record.getSid();
......
package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import org.apache.poi.hssf.record.*;
public class SSTRecordHandler extends AbstractXlsRecordHandler {
/**
* Record handler
*
* @author Dan Zheng
*/
public class SstRecordHandler extends AbstractXlsRecordHandler {
private SSTRecord sstRecord;
@Override
public boolean support(Record record) {
return SSTRecord.sid == record.getSid() || LabelSSTRecord.sid == record.getSid();
......
......@@ -12,7 +12,6 @@ import com.alibaba.excel.cache.ReadCache;
public class SharedStringsTableHandler extends DefaultHandler {
private static final String T_TAG = "t";
private String currentData;
private boolean isT;
private ReadCache readCache;
public SharedStringsTableHandler(ReadCache readCache) {
......
......@@ -2,10 +2,32 @@ package com.alibaba.excel.analysis.v07;
import org.xml.sax.Attributes;
/**
* Cell handler
*
* @author Dan Zheng
*/
public interface XlsxCellHandler {
/**
* Which tags are supported
*
* @param name
* @return
*/
boolean support(String name);
/**
* Start handle
*
* @param name
* @param attributes
*/
void startHandle(String name, Attributes attributes);
/**
* End handle
*
* @param name
*/
void endHandle(String name);
}
......@@ -2,12 +2,35 @@ package com.alibaba.excel.analysis.v07;
import com.alibaba.excel.metadata.CellData;
/**
* Result holder
*
* @author jipengfei
*/
public interface XlsxRowResultHolder {
/**
* Clear Result
*/
void clearResult();
/**
* Append current 'cellValue'
*
* @param currentCellValue
*/
void appendCurrentCellValue(String currentCellValue);
/**
* Get row content
*
* @return
*/
CellData[] getCurRowContent();
/**
* get column size
*
* @return
*/
int getColumnSize();
}
......@@ -8,6 +8,11 @@ import org.xml.sax.Attributes;
import com.alibaba.excel.analysis.v07.XlsxCellHandler;
import com.alibaba.excel.context.AnalysisContext;
/**
* Cell Handler
*
* @author jipengfei
*/
public class CountRowCellHandler implements XlsxCellHandler {
private final AnalysisContext analysisContext;
......
......@@ -21,7 +21,11 @@ import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.PositionUtils;
import com.alibaba.excel.util.StringUtils;
/**
* Cell Handler
*
* @author jipengfei
*/
public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder {
private final AnalysisContext analysisContext;
private String currentTag;
......
......@@ -9,6 +9,11 @@ import com.alibaba.excel.analysis.v07.XlsxRowResultHolder;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.event.EachRowAnalysisFinishEvent;
/**
* Cell Handler
*
* @author jipengfei
*/
public class ProcessResultCellHandler implements XlsxCellHandler {
private AnalysisContext analysisContext;
private XlsxRowResultHolder rowResultHandler;
......
......@@ -24,7 +24,7 @@ public interface ReadCache {
void put(String value);
/**
* Get
* Get value
*
* @param key
* @return
......@@ -32,12 +32,12 @@ public interface ReadCache {
String get(Integer key);
/**
* 所有
* It's called when all the values are put in
*/
void putFinished();
/**
*
* Called when the excel read is complete
*/
void destroy();
......
......@@ -64,6 +64,8 @@ public interface AnalysisContext {
/**
* Custom attribute
*
* @return
*/
Object getCustom();
......
......@@ -67,6 +67,7 @@ public interface WriteContext {
void finish();
/**
* Current sheet
*
* @return
* @deprecated please us e{@link #writeSheetHolder()}
......@@ -75,6 +76,7 @@ public interface WriteContext {
Sheet getCurrentSheet();
/**
* Need head
*
* @return
* @deprecated please us e{@link #writeSheetHolder()}
......@@ -83,7 +85,8 @@ public interface WriteContext {
boolean needHead();
/**
*
* Get outputStream
*
* @return
* @deprecated please us e{@link #writeWorkbookHolder()} ()}
*/
......@@ -91,7 +94,8 @@ public interface WriteContext {
OutputStream getOutputStream();
/**
*
* Get workbook
*
* @return
* @deprecated please us e{@link #writeWorkbookHolder()} ()}
*/
......
......@@ -40,7 +40,7 @@ public class DefaultConverterLoader {
* @return
*/
public static Map<String, Converter> loadDefaultWriteConverter() {
Map<String, Converter> converterMap = new HashMap<String, Converter>();
Map<String, Converter> converterMap = new HashMap<String, Converter>(16);
putWriteConverter(converterMap, new BigDecimalNumberConverter());
putWriteConverter(converterMap, new BooleanBooleanConverter());
putWriteConverter(converterMap, new ByteNumberConverter());
......@@ -64,7 +64,7 @@ public class DefaultConverterLoader {
* @return
*/
public static Map<String, Converter> loadDefaultReadConverter() {
Map<String, Converter> converterMap = new HashMap<String, Converter>();
Map<String, Converter> converterMap = new HashMap<String, Converter>(64);
putReadConverter(converterMap, new BigDecimalBooleanConverter());
putReadConverter(converterMap, new BigDecimalNumberConverter());
putReadConverter(converterMap, new BigDecimalStringConverter());
......
package com.alibaba.excel.metadata;
/**
* @author jipengfei
*/
public class IndexValue {
private String v_index;
private String v_value;
public IndexValue(String v_index, String v_value) {
super();
this.v_index = v_index;
this.v_value = v_value;
}
public String getV_index() {
return v_index;
}
public void setV_index(String v_index) {
this.v_index = v_index;
}
public String getV_value() {
return v_value;
}
public void setV_value(String v_value) {
this.v_value = v_value;
}
@Override
public String toString() {
return "IndexValue [v_index=" + v_index + ", v_value=" + v_value + "]";
}
}
......@@ -32,6 +32,17 @@ public enum ExcelTypeEnum {
FileMagic fileMagic = null;
if (file != null) {
fileMagic = FileMagic.valueOf(file);
if (!FileMagic.OLE2.equals(fileMagic) && !FileMagic.OOXML.equals(fileMagic)) {
String fileName = file.getName();
if (fileName.endsWith(XLSX.getValue())) {
return XLSX;
} else if (fileName.endsWith(XLS.getValue())) {
return XLS;
} else {
throw new ExcelCommonException("Unknown excel type.");
}
}
} else {
fileMagic = FileMagic.valueOf(inputStream);
}
......
package com.alibaba.excel.util;
import java.util.*;
import java.util.Collection;
import java.util.Map;
/**
* Miscellaneous collection utility methods.
* Mainly for internal use within the framework.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Arjen Poutsma
* @since 1.1.3
* Collection utils
*
* @author jipengfei
*/
public abstract class CollectionUtils {
public class CollectionUtils {
/**
* Return {@code true} if the supplied Collection is {@code null} or empty.
* Otherwise, return {@code false}.
* @param collection the Collection to check
* @return whether the given Collection is empty
*/
public static boolean isEmpty(Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
/**
* Return {@code true} if the supplied Map is {@code null} or empty.
* Otherwise, return {@code false}.
* @param map the Map to check
* @return whether the given Map is empty
*/
public static boolean isEmpty(Map<?, ?> map) {
return (map == null || map.isEmpty());
}
/**
* Convert the supplied array into a List. A primitive array gets converted
* into a List of the appropriate wrapper type.
* <p><b>NOTE:</b> Generally prefer the standard {@link Arrays#asList} method.
* This {@code arrayToList} method is just meant to deal with an incoming Object
* value that might be an {@code Object[]} or a primitive array at runtime.
* <p>A {@code null} source value will be converted to an empty List.
* @param source the (potentially primitive) array
* @return the converted List result
* @see ObjectUtils#toObjectArray(Object)
* @see Arrays#asList(Object[])
*/
@SuppressWarnings("rawtypes")
public static List arrayToList(Object source) {
return Arrays.asList(ObjectUtils.toObjectArray(source));
}
/**
* Merge the given array into the given Collection.
* @param array the array to merge (may be {@code null})
* @param collection the target Collection to merge the array into
*/
@SuppressWarnings("unchecked")
public static <E> void mergeArrayIntoCollection(Object array, Collection<E> collection) {
if (collection == null) {
throw new IllegalArgumentException("Collection must not be null");
}
Object[] arr = ObjectUtils.toObjectArray(array);
for (Object elem : arr) {
collection.add((E) elem);
}
}
/**
* Merge the given Properties instance into the given Map,
* copying all properties (key-value pairs) over.
* <p>Uses {@code Properties.propertyNames()} to even catch
* default properties linked into the original Properties instance.
* @param props the Properties instance to merge (may be {@code null})
* @param map the target Map to merge the properties into
*/
@SuppressWarnings("unchecked")
public static <K, V> void mergePropertiesIntoMap(Properties props, Map<K, V> map) {
if (map == null) {
throw new IllegalArgumentException("Map must not be null");
}
if (props != null) {
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
Object value = props.get(key);
if (value == null) {
// Allow for defaults fallback or potentially overridden accessor...
value = props.getProperty(key);
}
map.put((K) key, (V) value);
}
}
}
/**
* Check whether the given Iterator contains the given element.
* @param iterator the Iterator to check
* @param element the element to look for
* @return {@code true} if found, {@code false} else
*/
public static boolean contains(Iterator<?> iterator, Object element) {
if (iterator != null) {
while (iterator.hasNext()) {
Object candidate = iterator.next();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Enumeration contains the given element.
* @param enumeration the Enumeration to check
* @param element the element to look for
* @return {@code true} if found, {@code false} else
*/
public static boolean contains(Enumeration<?> enumeration, Object element) {
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
Object candidate = enumeration.nextElement();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Collection contains the given element instance.
* <p>Enforces the given instance to be present, rather than returning
* {@code true} for an equal element as well.
* @param collection the Collection to check
* @param element the element to look for
* @return {@code true} if found, {@code false} else
*/
public static boolean containsInstance(Collection<?> collection, Object element) {
if (collection != null) {
for (Object candidate : collection) {
if (candidate == element) {
return true;
}
}
}
return false;
}
/**
* Return {@code true} if any element in '{@code candidates}' is
* contained in '{@code source}'; otherwise returns {@code false}.
* @param source the source Collection
* @param candidates the candidates to search for
* @return whether any of the candidates has been found
*/
public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return false;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return true;
}
}
return false;
}
/**
* Return the first element in '{@code candidates}' that is contained in
* '{@code source}'. If no element in '{@code candidates}' is present in
* '{@code source}' returns {@code null}. Iteration order is
* {@link Collection} implementation specific.
* @param source the source Collection
* @param candidates the candidates to search for
* @return the first present object, or {@code null} if not found
*/
@SuppressWarnings("unchecked")
public static <E> E findFirstMatch(Collection<?> source, Collection<E> candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return null;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return (E) candidate;
}
}
return null;
}
/**
* Find a single value of the given type in the given Collection.
* @param collection the Collection to search
* @param type the type to look for
* @return a value of the given type found if there is a clear match,
* or {@code null} if none or more than one such value found
*/
@SuppressWarnings("unchecked")
public static <T> T findValueOfType(Collection<?> collection, Class<T> type) {
if (isEmpty(collection)) {
return null;
}
T value = null;
for (Object element : collection) {
if (type == null || type.isInstance(element)) {
if (value != null) {
// More than one value found... no clear single value.
return null;
}
value = (T) element;
}
}
return value;
}
/**
* Find a single value of one of the given types in the given Collection:
* searching the Collection for a value of the first type, then
* searching for a value of the second type, etc.
* @param collection the collection to search
* @param types the types to look for, in prioritized order
* @return a value of one of the given types found if there is a clear match,
* or {@code null} if none or more than one such value found
*/
public static Object findValueOfType(Collection<?> collection, Class<?>[] types) {
if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
return null;
}
for (Class<?> type : types) {
Object value = findValueOfType(collection, type);
if (value != null) {
return value;
}
}
return null;
}
/**
* Determine whether the given Collection only contains a single unique object.
* @param collection the Collection to check
* @return {@code true} if the collection contains a single reference or
* multiple references to the same instance, {@code false} else
*/
public static boolean hasUniqueObject(Collection<?> collection) {
if (isEmpty(collection)) {
return false;
}
boolean hasCandidate = false;
Object candidate = null;
for (Object elem : collection) {
if (!hasCandidate) {
hasCandidate = true;
candidate = elem;
}
else if (candidate != elem) {
return false;
}
}
return true;
}
/**
* Find the common element type of the given Collection, if any.
* @param collection the Collection to check
* @return the common element type, or {@code null} if no clear
* common type has been found (or the collection was empty)
*/
public static Class<?> findCommonElementType(Collection<?> collection) {
if (isEmpty(collection)) {
return null;
}
Class<?> candidate = null;
for (Object val : collection) {
if (val != null) {
if (candidate == null) {
candidate = val.getClass();
}
else if (candidate != val.getClass()) {
return null;
}
}
}
return candidate;
}
/**
* Marshal the elements from the given enumeration into an array of the given type.
* Enumeration elements must be assignable to the type of the given array. The array
* returned will be a different instance than the array given.
*/
public static <A, E extends A> A[] toArray(Enumeration<E> enumeration, A[] array) {
ArrayList<A> elements = new ArrayList<A>();
while (enumeration.hasMoreElements()) {
elements.add(enumeration.nextElement());
}
return elements.toArray(array);
}
/**
* Adapt an enumeration to an iterator.
* @param enumeration the enumeration
* @return the iterator
*/
public static <E> Iterator<E> toIterator(Enumeration<E> enumeration) {
return new EnumerationIterator<E>(enumeration);
}
/**
* Iterator wrapping an Enumeration.
*/
private static class EnumerationIterator<E> implements Iterator<E> {
private final Enumeration<E> enumeration;
public EnumerationIterator(Enumeration<E> enumeration) {
this.enumeration = enumeration;
}
@Override
public boolean hasNext() {
return this.enumeration.hasMoreElements();
}
@Override
public E next() {
return this.enumeration.nextElement();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not supported");
}
}
}
......@@ -20,6 +20,7 @@ public class FileUtils {
private static final String POIFILES = "poifiles";
private static final String CACHE = "excache";
private static final int WRITE_BUFF_SIZE = 8192;
/**
* Write inputStream to file
......@@ -32,8 +33,8 @@ public class FileUtils {
try {
outputStream = new FileOutputStream(file);
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
byte[] buffer = new byte[WRITE_BUFF_SIZE];
while ((bytesRead = inputStream.read(buffer, 0, WRITE_BUFF_SIZE)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
......@@ -98,7 +99,7 @@ public class FileUtils {
}
File directory = new File(tmpDir, path);
if (!directory.exists()) {
syncCreatePOIFilesDirectory(directory);
syncCreatePoiFilesDirectory(directory);
}
return directory;
}
......@@ -107,7 +108,7 @@ public class FileUtils {
*
* @param directory
*/
private static synchronized void syncCreatePOIFilesDirectory(File directory) {
private static synchronized void syncCreatePoiFilesDirectory(File directory) {
if (!directory.exists()) {
directory.mkdirs();
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册