Are there any programming errors in this java code?

    import java.lang.*;
import java.io.*;

class test 
{
    public static void main(String[] a) throws Exception
    {
        int i;
        String[] str = new String[]{"javac","example.java"};
        String[] str1 = new String[]{"java","example"};
        Runtime r = Runtime.getRuntime();
        Process p = null;
        Process p1 = null;
        p=r.exec(str);
        p1=r.exec(str1);
        InputStreamReader reader = new InputStreamReader (p1.getInputStream ());
        BufferedReader br = new BufferedReader(reader);
        FileWriter fw = new FileWriter("this.txt",true);
        char[] c = new char[1];
        while ((i=br.read())!=-1)
        {
            c[0]     = (char) i ;
            fw.write(c);
            c = new char[1];
        }
        fw.close();
    }
}

This is a simple program that uses the runtime class. Is there any cessation of using process code?

Thanks in advance!

+3
source share
6 answers

1. There is no reason to initialize process objects to zero.

Just do:

Process p = r.exec(str);
Process p1 = r.exec(str1);

While you're on it, better variable names would help

2. You can improve performance by reading and writing more than 1 character at a time:

3. You can explicitly specify encodings, and not use the default platform.

InputStreamReader reader = new InputStreamReader (p1.getInputStream (), inputCharsetName);
BufferedReader br = new BufferedReader(reader);
FileOutputStream fos = new FileOutputStream("this.txt", true);
Writer writer = new OutputStreamWriter(fos, outputCharsetName);
+4
source

The input stream never closes, and I recommend closing the entry in the finally block.

+3
source

Process.waitFor(), . , , , .

, , - char[] c = new char[1]; // lolz array with exactly one element, .

+1

- ?

, - ? ( , , ?)

:

p.destroy();
p1.destroy();
0

, . . example.class , example.java.

0

-, . waitFor():

int compilationResult = -1;
try {
  compilationresult = p.waitFor();
}
catch (InterruptedException ie) {
  ...
}

compilationResult ( 0 ), , .

-, p1 , , - , .

, , p1.waitFor() try/catch.

, :

p1.destroy();

, , , p1.exitValue(). ? , , , , this.txt, , .

0
source

Source: https://habr.com/ru/post/1752202/


All Articles