可能我正在使用 MultipartFile 上传功能来完成此操作。
我必须从 csv 文件中读取数据,该文件将由客户端通过浏览器选择。我使用 MultipartFile 来上传文件。该文件即将发送到控制器,但现在我无法从中读取 csv 数据。请指导最佳方法或帮助我从 MultipartFile 读取 csv 数据。 jsp 有
<form method="POST" action="uploadFile" enctype="multipart/form-data">
File to upload: <input type="file" name="file"> <input
type="submit" value="Upload"> Press here to upload the
file!
</form>
控制器有
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
谢谢。
我使用缓冲区逐行读取并从多部分输入流中获取。也许是更多的代码,但我发现按行读取文本文件很有帮助。
BufferedReader br;
List<String> result = new ArrayList<>();
try {
String line;
InputStream is = multipart.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
result.add(line);
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
我想出了一个解决方法。我将文件转换为字节,然后将字节转换为字符串。从 String 中,我应用了 string.split() 从文件中获取我想要的内容。
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
String completeData = new String(bytes);
String[] rows = completeData.split("#");
String[] columns = rows[0].split(",");
我发现的最好的解决方案是
@PostMapping(value="/csv")
public ResponseEntity<Void> processUpload(@RequestParam MultipartFile file) {
BufferedReader fileReader = new BufferedReader(new
InputStreamReader(file.getInputStream(), "UTF-8"));
CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT);
Iterable<CSVRecord> csvRecords = csvParser.getRecords();
for (CSVRecord csvRecord : csvRecords) {
System.out.println(csvRecord);
}
...
的自适应解决方案
也许您可以尝试使用通用实用程序将 CSV 转换为 POJO 并扩展到其他数据类型
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.opencsv.bean.CsvToBeanBuilder;
import stocktales.durations.UtilDurations;
public class CSV2POJOUtility
{
@SuppressWarnings(value =
{ "rawtypes", "unchecked" })
public static <T> List<T> getPOJOS4mCsv(String filePath, Class<T> pojoClass) throws Exception
{
List<T> pojos = null;
if (StringUtils.hasText(filePath))
{
if (pojoClass != null)
{
File file = new File(filePath);
if (file != null)
{
FileInputStream fileStream;
try
{
fileStream = new FileInputStream(file);
Reader reader = new InputStreamReader(fileStream);
if (reader != null)
{
pojos = (List<T>) new CsvToBeanBuilder(reader).withSkipLines(1)
.withType(pojoClass.getClass()).build().parse();
}
}
catch (Exception e)
{
//Try from Class Path instead
file = ResourceUtils.getFile("classpath:" + filePath);
if (file != null)
{
try
{
fileStream = new FileInputStream(file);
Reader reader = new InputStreamReader(fileStream);
if (reader != null)
{
pojos = (List<T>) new CsvToBeanBuilder(reader).withSkipLines(1).withType(pojoClass)
.build().parse();
}
}
catch (Exception e1)
{
throw e1;
}
}
}
}
}
}
return pojos;
}
public static <T> List<T> getPOJOS4mCsv(MultipartFile file, Class<T> pojoClass, boolean skipFirstLine)
throws Exception
{
List<T> pojos = null;
if (!file.isEmpty())
{
if (pojoClass != null)
{
if (file.getInputStream() != null)
{
BufferedReader fileReader = new BufferedReader(
new InputStreamReader(file.getInputStream(), "UTF-8"));
CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT);
Iterable<CSVRecord> csvRecords = csvParser.getRecords();
if (csvRecords.iterator() != null)
{
long cnt = 0;
pojos = new ArrayList<T>();
// Get the fields of the class object
Field[] fields = pojoClass.getDeclaredFields();
List<Method> methods = getSetters(pojoClass);
List<Field> fieldsList = Arrays.asList(fields);
if (CollectionUtils.isNotEmpty(methods) && CollectionUtils.isNotEmpty(fieldsList))
{
for (CSVRecord csvRecord : csvRecords)
{
cnt += 1;
if (skipFirstLine)
{
if (cnt > 1)
{
setFlds(pojoClass, pojos, methods, fieldsList, csvRecord);
}
}
else
{
setFlds(pojoClass, pojos, methods, fieldsList, csvRecord);
}
}
}
}
csvParser.close();
}
}
}
return pojos;
}
private static <T> void setFlds(Class<T> pojoClass, List<T> pojos, List<Method> methods, List<Field> fieldsList,
CSVRecord csvRecord) throws Exception
{
Object classObject = (T) pojoClass.newInstance();
int fldCnt = 0;
//Number of Columns must equal Setter Methods
if (csvRecord.size() == methods.size())
{
for (Field field : fieldsList)
{
Method method = methods.stream().filter(m -> m.getName().toLowerCase().contains(field.getName()))
.findFirst().get();
if (method != null)
{
Object val = csvRecord.get(fldCnt);
if (field.getType().equals(Date.class))
{
Date valDate = UtilDurations.getDateFromString(val.toString());
method.invoke(classObject, valDate);
}
else
{
method.invoke(classObject, val);
}
fldCnt++;
}
}
}
pojos.add((T) classObject);
}
public static List<Method> getSetters(Class<?> c)
{
List<Method> setters = new ArrayList<>();
for (Method method : c.getDeclaredMethods())
{
if (method.getName().startsWith("set") && method.getParameterCount() == 1)
{
setters.add(method);
}
}
return setters;
}
}