[英]file input to spring boot application
I have a text file containing phone numbers which is new line seperated, I want to pass this file to the spring boot application, and copy the content of the file into the list. 我有一个包含电话号码的文本文件,该文件用新行分隔,我想将此文件传递给spring boot应用程序,然后将文件内容复制到列表中。
@RequestMapping(value = "/FileUpload", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> FileUpload(@RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpServletResponse response) {
....
}
thanks :) 谢谢 :)
Here is a complete example for reading a text file and returning it's content as strping comma sparated numbers : 这是读取文本文件并将其内容返回为以逗号分隔的数字形式的完整示例:
@RequestMapping(value = "/FileUpload", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> FileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
List<String> numbers = new ArrayList<String>();
InputStream inputStream = file.getInputStream();
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream));
String numberLine;
while ((numberLine = bufferReader.readLine()) != null) {
numbers.add(numberLine);
}
bufferReader.close();
/* pint all numbers */
numbers.forEach(System.out::println):
String result = String.join(",", numbers);
return new ResponseEntity<String>(result, HttpStatus.OK);
}
you should write a function to create a list from a MultipartFile using a BufferedReader to get every number line by line. 您应该编写一个函数,使用BufferedReader从MultipartFile创建列表,以逐行获取每个数字。 Here's what you can do with a BufferedReader: 这是您可以使用BufferedReader进行的操作:
String line;
List<String> numberList = new ArrayList<>()
val bufferedReader = BufferedReader(new FileReader(myFile));
do {
line = bufferedReader.readLine();
if(line != null) {
numbersList.add(line);
}
} while (line != null)
bufferedReader.close()
Maybe you'll have to write some additional code to fit with your needs, but it should do the job. 也许您必须编写一些其他代码来满足您的需求,但这应该可以完成工作。 Try this and tell me if it works, I didn't test with MultipartFile. 试试这个,告诉我是否可行,我没有使用MultipartFile进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.