Search code examples
javafile-iobufferedreader

why i cant export all line to text file?


my code is creating empty text file although I have tried to use the same code which used to work for small data output

text file output should look like this

ClassMetrics 3 1 0 3 18 0 0 3 2 0.0000 66 1.0000 0 0.0000 0.5556 0 0 20.6667

~ void (): 1

~ public gr.spinellis.ckjm.ClassMetrics getMetrics(String arg0): 2

~ public void printMetrics(gr.spinellis.ckjm.CkjmOutputHandler arg0): 3

but I get an empty text file

this is the source code

package javaapplication11;

import java.io.*;

public class CmdTest {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder("cmd.exe","/c",
                "java -jar C:\\Users\\hp\\Desktop\\ckjm-1.99.jar  C:\\Users\\hp\\Desktop\\*.class");

        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) {
                break;
            }
            PrintWriter writer = new PrintWriter("C:\\Users\\hp\\Desktop\\result3.txt", "UTF-8");
            // writer.println("\t\t\tWMC DIT NOC CBO RFC LCOM Ce NPM");
            System.out.println(line);
            writer.write(line);
            writer.close();
        }
    }
}

Solution

  • The problem is that you open and close the writer repeatedly within the loop. Every time you create the writer, it overwrites the previous content of the output file, so the file contains only one line at a time. If the last line in your input file happens to be empty, the resulting output file will be empty as well.

    If you change your while loop like this, it will behave correctly:

    PrintWriter writer = new PrintWriter("C:\\Users\\hp\\Desktop\\result3.txt", "UTF-8");
    while (true) {
            line = r.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
            writer.write(line);
    }
    writer.close();
    

    Well, the code above will work if everything goes right. We must ensure that the writer gets closed if an error occurs, for which there is the try-with-resources statement. The really correct code would look like this.

    try (PrintWriter writer = new PrintWriter("C:\\Users\\hp\\Desktop\\result3.txt", "UTF-8"))
        String line;
        while ( (line = r.readLine()) != null) {
            System.out.println(line);
            writer.write(line);
        }
    }