Answer the question
In order to leave comments, you need to log in
Why are there different values when outputting to the console and to a text file?
In the code, you need to write something to the file several times - writing occurs in void main and in one function inside void main. In a nested function, when outputting to the console, everything is beautiful, but it simply doesn’t work to output the same thing to a file - either garbage is output from scraps of what was in the console, or nothing is output (depending on where to initialize FileWriter). Do you need advice on how to organize this or what could be the problem?
public class Main {
public static void main(String[] args) throws IOException {
FileWriter err = new FileWriter("error.txt");
myFunction(args);
//some logic
err.write(something);
err.close();
}
private static void myFunction(String url) throws IOException {
FileWriter er = new FileWriter("error.txt");
if (some condition) {
er.write(url + " " + statusCode + "\n"); //вообще ничего не пишет в файл
System.err.println(url + " " + statusCode); //выводит всё как надо
return;
}
er.close();
}
}
}
Answer the question
In order to leave comments, you need to log in
Because the return
method terminates, er.close()
it is not called and the file is not written to.
Read about SOLID ( https://ru.wikipedia.org/wiki/SOLID_(%D0%BE%D0%B1%...
There the letter S stands for single responsibility).
Try to write methods and classes that will perform just one function.
In your case, myFunction should not be able to write to a file - it will be enough for it to be able to process the incoming string. It will look something like this:
private static String myFunction(String url) {
if (some condition) {
System.err.println(url + " " + statusCode); // Видимо, логирование в консоль
return url + " " + statusCode + "\n"; // Возврат результата
}
return ""; // Это же пример, верно?))
}
public static void main(String[] args) throws IOException {
FileWriter err = new FileWriter("error.txt");
String result = myFunction(args);
er.write(result);
//some logic
err.write(something);
err.close();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question