Question 2
Back to Exercise
Write sales.csv (region,product,amount), read it with Files.lines, total the amount per region, and write a sorted report.txt with PrintWriter; print the report.
Solution
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("sales");
Path csv = dir.resolve("sales.csv"), report = dir.resolve("report.txt");
Files.write(csv, List.of("region,product,amount", "North,Pen,1200", "South,Book,4500", "North,Bag,9000", "West,Pen,800", "South,Pen,1500"));
Map<String, Integer> totals;
try (Stream<String> lines = Files.lines(csv)) {
totals = lines.skip(1).map(l -> l.split(","))
.collect(Collectors.groupingBy(p -> p[0], TreeMap::new, Collectors.summingInt(p -> Integer.parseInt(p[2]))));
}
try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(report))) {
pw.println("SALES BY REGION");
totals.forEach((r, t) -> pw.printf("%-6s %,8d%n", r, t));
pw.printf("%-6s %,8d%n", "TOTAL", totals.values().stream().mapToInt(Integer::intValue).sum());
}
System.out.print(Files.readString(report));
Files.delete(csv); Files.delete(report); Files.delete(dir);
}
}
SALES BY REGION North 10,200 South 6,000 West 800 TOTAL 17,000
Files.lines streams the input, a collector aggregates it, and PrintWriter formats the output file.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!