Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write multiple lines in a text file ( java)

Tags:

java

This following code is to run a command in cmd and to produce a text file with the output from the command line. The code below shows the correct information in the output window in Eclipse, but only one last line is printed in the text file. Can anyone help me with this?

import java.io.*;

public class TextFile {
public static void main(String[] args) throws IOException {
    try {
        Process p = Runtime.getRuntime().exec("git log");

        BufferedReader in = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
        BufferedWriter writer = null;

        String line = null;
        while ((line = in.readLine()) != null) {

            writer = new BufferedWriter(new FileWriter("textfile.txt"));
            writer.write(line);
            System.out.println(line);

            writer.close();
        }

    } catch (IOException e) {
        e.printStackTrace();

    }

   }
}
like image 344
Laura Ruby Avatar asked Feb 26 '26 11:02

Laura Ruby


1 Answers

As stated in other answer, problem is that you are creating BufferedWriter instance inside while loop and that is why only last line is getting printed in file.

One of the better way to write this program using try-with-resources -

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class TextFile {

    public static void main(String[] args) throws IOException {
        try {
            Process p = Runtime.getRuntime().exec("git log");

            try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    BufferedWriter writer = new BufferedWriter(new FileWriter("textfile.txt"))) {

                String line = null;
                while ((line = in.readLine()) != null) {
                    writer.write(line);
                    writer.newLine();
                    System.out.println(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}
like image 98
Vikas Sachdeva Avatar answered Feb 28 '26 00:02

Vikas Sachdeva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!