Content is not being saved to the file using the Printwriter class

Asked

Viewed 58 times

0

The file, in fact, is created, but without the content it should have.

inserir a descrição da imagem aqui

Method Program:

String program() {

        return "import java.io.*;\n"
                + "import javax.swing.JOptionPane;\n"
                + "\n"
                + "public class Main {\n"
                + "    \n"
                + "    static final Runtime run = Runtime.getRuntime();\n"
                + "    static Process pro;\n"
                + "    static BufferedReader read;\n"
                + "\n"
                + "    public static void main(String[] args) {\n"
                + "        String[] cmds = {\n"
                + "            \"cd /d D:\\\\Desenvolvimento\\\\snippets-codes && concurrently \\\"cd snippets && serve\\\" \\\"cd backend && adonis serve --dev\\\"\",\n"
                + "        };\n"
                + "\n"
                + "        try {\n"
                + "            ProcessBuilder builder = new ProcessBuilder(\"cmd\", \"/c\",\n"
                + "                    String.join(\"& \", cmds));\n"
                + "\n"
                + "            builder.redirectErrorStream(true);\n"
                + "\n"
                + "            Process p = builder.start();\n"
                + "\n"
                + "            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));\n"
                + "            String line;\n"
                + "\n"
                + "            while (true) {\n"
                + "                line = r.readLine();\n"
                + "                if (line == null) {\n"
                + "                    break;\n"
                + "                }\n"
                + "\n"
                + "                System.out.println(line);\n"
                + "            }\n"
                + "        } catch (Exception e) {\n"
                + "            JOptionPane.showMessageDialog(null, e.getMessage(), \"Atenção\", 1);\n"
                + "        }\n"
                + "    }\n"
                + "}";
    }

Code to create the file and insert some content into it:

try {
      PrintWriter writer = new PrintWriter("C:\\Users\\MY_USER_NAME\\Desktop\\teste.java", "UTF-8");

            String[] words = program().split("\\n");

            for (String word : words) {
                System.out.println(word);
                writer.println(word);
            }

        } catch (FileNotFoundException | UnsupportedEncodingException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Atenção", 1);
        }

2 answers

2


Internally, PrintWriter has a buffer in which the writings are made. When the buffer is full, there its content is actually written in stream corresponding (in this case, the file). In your case, the content was not enough to fill the buffer, so nothing was written.

There are some alternatives to solve.

One of them is, in the end, to call the method flush, that forces the writing of the content that is in buffer:

for (String word : words) {
    System.out.println(word);
    writer.println(word);
}
writer.flush();

Another is to call the method close, preferably within a block finally (for the close() already does the flush):

PrintWriter writer = null;
try {
    writer = new PrintWriter("teste.java", "UTF-8");
    String[] words = program().split("\\n");

    for (String word : words) {
        System.out.println(word);
        writer.println(word);
    }
} catch (IOException e) {
    // tratar a exceção
} finally {
    if (writer != null)
        writer.close();
}

But if you are using Java >= 7, you can use the syntax of Try-with-Resources:

try (PrintWriter writer = new PrintWriter("teste.java", "UTF-8")) {
    String[] words = program().split("\\n");

    for (String word : words) {
        System.out.println(word);
        writer.println(word);
    }
} catch (IOException e) {
    // tratar a exceção
}

In this case you don’t even need the block finally, for the PrintWriter will already be closed at the end of the block try (and when it is closed, the flush).


Another alternative is to use a builder which receives as a parameter the value of autoFlush, indicating whether the flush automatic:

PrintWriter writer = new PrintWriter(new FileWriter("teste.java"), true);

Passing the value true for autoFlush, is made the flush automatic every time the methods are called println, printf or format (so you don’t have to call flush or close to force the writing of the contents of buffer).

Although I particularly prefer the blocks try above (Try-with-Resources if using Java >= 7, or try/finally for previous versions), to ensure that the resource is closed.

0

Flush and Close are missing

    try {
        PrintWriter writer = new PrintWriter("C:\\Users\\MY_USER_NAME\\Desktop\\teste.java", "UTF-8");

        String[] words = program().split("\\n");

        for (String word : words) {
            System.out.println(word);
            writer.println(word);
        }

        writer.flush();
        writer.close();

    } catch (FileNotFoundException | UnsupportedEncodingException ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage(), "Atenção", 1);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.