代码如下:
@Service
@Slf4j
public class WhiteService {
public List<String> readFromFile(WhiteFile file) throws IOException {
List<String> list = new ArrayList<String>();
//1.判断文件是否存在
if(file.getFile().isEmpty()||file.getFile().getSize()<0){
log.warn("file data got zero :{}",file.getName());
return new ArrayList<>();
}
//2.解析文件
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getFile().getInputStream()));
try{
String lineTxt;
while((lineTxt = bufferedReader.readLine()) != null){
list.add(lineTxt);
}
bufferedReader.close();
}catch (Exception e){
log.error(e.getMessage());
}finally {
bufferedReader.close();
}
return list;
}
}
public class WhiteFile {
@JSONField(serialize = false)
private MultipartFile file;
private String key;
private String name;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
下载文件
private void createTxtFile(HttpServletResponse response, String filename, String Metadata) {
// 让servlet用UTF-8转码,默认为ISO8859
response.setCharacterEncoding("UTF-8");
response.setContentType("text/csv");
response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s.csv\"", filename));
try {
OutputStream outputStream = response.getOutputStream();
String[] strings=Metadata.split(",");
for(int i=0;i<strings.length-1;i++){
outputStream.write(strings[i].getBytes(StandardCharsets.UTF_8));
outputStream.write(",".getBytes(StandardCharsets.UTF_8));
outputStream.write("\r\n".getBytes());
}
outputStream.write(strings[strings.length-1].getBytes(StandardCharsets.UTF_8));
outputStream.write(",".getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
} catch(Exception e) {
e.printStackTrace();
}
}