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

. #1610

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

. #1610

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
36 changes: 36 additions & 0 deletions src/main/java/core/basesyntax/WorkWithFile.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,43 @@
package core.basesyntax;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

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

try (BufferedReader reader = Files.newBufferedReader(Paths.get(fromFileName))) {
String line = " ";

Choose a reason for hiding this comment

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

The initialization of the line variable with a space (" ") is unnecessary. It can be initialized as an empty string ("") or simply declared without initialization, as it will be immediately overwritten by reader.readLine().

while ((line = reader.readLine()) != null){
String [] parts = line.split(",");
if (parts.length == 2) {
String operation = parts[0].trim();
int amount = Integer.parseInt(parts[1].trim());
if ("supply".equalsIgnoreCase(operation)) {
supply += amount;
} else if ("buy".equalsIgnoreCase(operation)){
buy += amount;
}
}
}
} catch (IOException e) {
throw new RuntimeException(fromFileName, e);
}
int result = supply - buy;

try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(toFileName))) {
writer.write("supply," + supply);
writer.newLine();
writer.write("buy," + buy);
writer.newLine();
writer.write("result," + result);
} catch (IOException e) {
System.err.println("Error writing to the file: " + e.getMessage());

Choose a reason for hiding this comment

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

Using System.err.println for error handling is not ideal for production code. Consider throwing an exception or using a logging framework to handle errors more gracefully.

}
}
}
Loading