Reputation: 61
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();
}
}
}
Upvotes: 3
Views: 31294
Reputation: 5813
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();
}
}
}
Upvotes: 3
Reputation: 20824
The problem is that you are creating a new BufferedWriter within the loop. Secondarily, you are also closing the writer inside the loop. Finally, your code blocks are a little confusing - if you reformat your code (do it automatically with Ctrl-F in Eclipse), the blocks in your code will be more clear.
Your code should look like this, inside the try
portion of the try/catch block:
BufferedWriter writer = (new FileWriter ("textfile.txt"));
String line =null;
while ((line= in.readLine()) !=null) {
writer.write(line);
System.out.println(line);
}
writer.close();
Upvotes: 0