读取resources目录下的excel文件:
// @Component 和 @PostConstruct 配合,项目启动时执行。
@Component
public class AppStartConfig {
protected static final Logger logger = LoggerFactory.getLogger(AppStartConfig.class);
@PostConstruct
public void readStaticResources() throws IOException {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:\\data\\static\\*.xlsx");
logger.info("resources:{}", (Object) resources);
String path = "C:\\Users\\Name.last\\Desktop";
for (Resource res : resources) {
logger.info("开始处理文件:{}", res);
byte[] data = readFileToByteArray(res);
writeByteArrayToFile(data,path,res.getFilename());
logger.info("处理文件结束!");
}
}
public byte[] readFileToByteArray(Resource resource) {
// 文件输入流(需要关闭)
InputStream is = null;
try {
is = resource.getInputStream();
// 字节数组输出流(不需要关闭)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024 * 2];
int len;
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
baos.flush();
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public void writeByteArrayToFile(byte[] data, String path, String fileName) {
// 文件输出流(需要关闭)
OutputStream os = null;
try {
os = new FileOutputStream(new File(path, fileName));
// 字节数组输入流(不需要关闭)
InputStream is = new ByteArrayInputStream(data);
byte[] buf = new byte[1024 * 2];
int len;
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}