Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution #1629

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/main/java/core/basesyntax/WorkWithFile.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
package core.basesyntax;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class WorkWithFile {
public void getStatistic(String fromFileName, String toFileName) {
int supplyTotal = 0;
int buyTotal = 0;

try {
List<String> lines = Files.readAllLines(Path.of(fromFileName));
for (String line : lines) {
String[] parts = line.split(",");
int sum = Integer.parseInt(parts[1]);
if(parts[0].equals("supply")) {
supplyTotal += sum;
} else if (parts[0].equals("buy")) {
buyTotal += sum;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
int result = supplyTotal - buyTotal;

String report = "supply," + supplyTotal + System.lineSeparator()
+ "buy," + buyTotal + System.lineSeparator()
+ "result," + result;

try {
Files.write(Path.of(toFileName), report.getBytes());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using StandardOpenOption.CREATE and StandardOpenOption.TRUNCATE_EXISTING with Files.write to ensure the file is created if it doesn't exist and truncated if it does. This will make your file writing operation more robust.

} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
Loading