i tried to copy the result of the java compilation to the text file using
javac zz.java > compile.txt

It works if the program has no errors and it did not work if it have errors

Dani AI

Generated

The compiler prints errors and warnings to the process standard error stream, not to standard output. That is why redirecting only stdout produced an empty file when compilation failed. hit the expected behavior; the replies from and are on the right track (shell-level stderr redirection and reading the error stream from a subprocess).

To capture diagnostics at the shell level, redirect stderr into the file (or merge stderr into stdout). On Windows CMD, redirect stdout and then send stderr into it; on Unix shells you can merge streams in one step. Use the appropriate form for the shell in use. For appending instead of overwriting, use the append variants.

For programmatic control inside Java, prefer ProcessBuilder over Runtime.exec because it gives explicit stream redirection and better control. Example approach:

ProcessBuilder pb = new ProcessBuilder("javac", "Main.java");
pb.redirectOutput(new File("compile.txt"));
pb.redirectErrorStream(true); // merge stderr into stdout
Process p = pb.start();
int rc = p.waitFor(); // wait so file is complete

For tools that need structured feedback (not plain text parsing), use the Java Compiler API (javax.tools.JavaCompiler) and a DiagnosticCollector to receive strongly typed diagnostics:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diag = new DiagnosticCollector<>();
StandardJavaFileManager fm = compiler.getStandardFileManager(diag, null, null);
Iterable<? extends JavaFileObject> units = fm.getJavaFileObjectsFromStrings(Arrays.asList("Main.java"));
boolean ok = compiler.getTask(null, fm, diag, null, null, units).call();
for (Diagnostic<? extends JavaFileObject> d : diag.getDiagnostics()) System.out.println(d);

Troubleshooting: confirm javac is on PATH, check file permissions, and ensure the process has finished (waitFor) before reading the file. Use exit codes or DiagnosticCollector results for reliable automation rather than parsing text output.

Recommended Answers

All 2 Replies

>and it did not work if it have errors.
Try to execute javac.exe as a subprocess using Runtime.exec method and get error output of subprocess using Process.getErrorStream() method.

String []cmd={"javac.exe","Sample.java"};
     Process proc=Runtime.getRuntime().exec(cmd);
     java.io.InputStream in=proc.getErrorStream();

you can also try,

javac zz.java 2> compile.txt

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.