I have a file with name numbs.txt having numbers 3,1,2 seperated by line.
I want to write a java program to read those numbers and print sum as 3+1+2=6.
            Asked
            
        
        
            Active
            
        
            Viewed 332 times
        
    1 Answers
0
            
            
        Because all the duplicate posts for that (the ones with are cites) are a bit old, I would suggest easy way (and more recent) to achieve that :
public static int method1(String path) throws IOException {
    int sum = 0;
    for (String line : Files.readAllLines(Paths.get(path)))
        sum += Integer.parseInt(line);
    return sum;
}
public static int method2(String path) throws IOException {
    return Files.readAllLines(Paths.get(path)).stream().mapToInt(Integer::parseInt).sum();
}
Files.readAllLines(somePath) returns a List<String> so the frst method will iterate with a classic for each loop, parse to Integer and sum. The second method will do the same with another syntax, using latest API of Java 8  : Streams (iterate and do same)
To use :
public static void main(String[] args) throws IOException {
    System.out.println(method1("numbs.txt"));  // if file is not in same folder
    System.out.println(method2("numbs.txt"));  //use absolute path: C:\users\...\numbs.txt
}
 
    
    
        azro
        
- 53,056
- 7
- 34
- 70
