Home > OS >  How to sum numbers From a CSV File and output it to TXT File In Java?
How to sum numbers From a CSV File and output it to TXT File In Java?

Time:07-27

I have CSV flie in flie like this

5,4,3,2,1

1,2,3,4,5

6,7,8,9,10

and I want to sum all number and I have to get output is TXT file

CodePudding user response:

  public static void main(String[] args) throws IOException {
    Path source = Path.of("src/sample.csv");
    Path dest = Path.of("src/result.txt");

    try (var s = Files.lines(source);
        var d = Files.newBufferedWriter(dest)) {

      int sum = s.map(f -> f.split(","))
          .flatMap(Arrays::stream)
          .mapToInt(Integer::parseInt)
          .sum();

      d.write(String.valueOf(sum));
    }
  }
  • Related