Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any programming defects in this Java code?

Tags:

java

runtime

    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 a simple program using runtime class. is there any termination of 'process' code need to be employed?

Thanks in advance!!!

like image 808
billu Avatar asked Jun 27 '26 21:06

billu


2 Answers

1 . There's no reason to initialize the process objects to null.

Just do:

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

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

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

3 . You may want to explicitly specify encodings, rather than using the platform default.

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);
like image 102
Matthew Flaschen Avatar answered Jul 01 '26 00:07

Matthew Flaschen


The input stream is never closed, and I recommend closing the writer in a finally block.

like image 39
Adam Crume Avatar answered Jul 01 '26 02:07

Adam Crume



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!