一、读文件
import static org.apache.ibatis.io.Resources.getResourceAsStream;
import org.apache.commons.io.IOUtils;
public String readFile(String fileName) throws IOException {
InputStream in = getResourceAsStream(fileName);
assert in != null;
List<String> lineList = IOUtils.readLines(in, "utf-8");
return lineList.parallelStream().reduce((a, b) -> a + "\n" + b).orElse("");
}
ps: fileName有绝对路径和相对路径的问题
二、写文件
public void writeFile() {
String path= "文件目录和文件名字,例如/data/test.sql";
File file=new File(path);
if(!file.exists()) {
file.createNewFile();
}
try(FileOutputStream out=new FileOutputStream(file, false)){
StringBuffer sb = new StringBuffer();
sb.append("要写入的内容");
//注意需要转换对应的字符集
out.write(sb.toString().getBytes("utf-8"));
} catch (Exception e){
logger.error(e.getMessage());
}
return path;
}
三、写EXCEL
public File wirteExcel(List<List<List<String>>> allSheets) throws Exception{
try {
String filePath = "这是即将要写的文件.xlsx";
OutputStream out = new FileOutputStream(filePath);
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);
int i = 1;
for(List<List<String>> siglesheet : allSheets) {
Sheet sheet = new Sheet(i, 0);
sheet.setSheetName("sheet" + i);
writer.write0(siglesheet, sheet);
i++;
}
writer.finish();
File file = new File(filePath);
Long fileSize = file.getTotalSpace();
if(file.exists() && file.isFile()){
return file;
}
}