文件输入到Spring Boot应用程序

时间:2019-01-10 10:42:49

标签: java spring spring-boot

我有一个包含电话号码的文本文件,该文件用新行分隔,我想将此文件传递给spring boot应用程序,然后将文件内容复制到列表中。

import java.util.Scanner;

public class Histogram {

   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the total size : ");
      int n= scanner.nextInt();
      int [] values = new int[n];
      int [] count = new int[9];
      int max = 0;
      System.out.println("Enter "+ n +" numbers between 1 to 9 :");
      for(int i=0;i<n;i++) {
          values[i] = scanner.nextInt();
          ++count[values[i]];
          if(count[values[i]] >max)
              max=count[values[i]];
      }
      histogram(max, count);

   }

   static void histogram(int max, int[] count) {
      for(int i=max;i>0;i--) {
          for(int j=0;j<9;j++) {
              if(count[j]>=i) {
                  System.out.print("* ");
              }else {
                  System.out.print("  ");
              }
          }
          System.out.println();
      }
      for(int i=0;i<=9;i++)
          System.out.print(i+" ");
    }
 }

谢谢:)

2 个答案:

答案 0 :(得分:1)

这是读取文本文件并将其内容返回为以逗号分隔的数字的完整示例:

@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);
}

答案 1 :(得分:0)

您应该编写一个函数,使用BufferedReader从MultipartFile创建列表,以逐行获取每个数字。这是您可以使用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()

也许您必须编写一些其他代码来满足您的需求,但这应该可以完成工作。试试这个,告诉我是否可行,我没有使用MultipartFile进行测试。