D
D
DiseaseC2020-09-27 18:46:02
Java
DiseaseC, 2020-09-27 18:46:02

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

2 answer(s)
S
Sergey Gornostaev, 2020-09-27
@DiseaseC

Because the returnmethod terminates, er.close()it is not called and the file is not written to.

D
Dmitry Roo, 2020-09-27
@xez

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 "";    // Это же пример, верно?))
    }

And the main code:
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();
    }

In this version, myFunction knows nothing about where to write the result of its work. Today you want to write to a file, tomorrow to a database, and then it turns out that it is enough to output to the console. Your function will remain unchanged anyway.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question