Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  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));
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading