Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

Wednesday, 20 November 2013

Code to save command prompt data to text file

Program:

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;

import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author mpamujula
 */
public class Getdata {
 
    public static void main(String args[]) throws IOException{
        File file = new File("d:\\Command_file.bat");
                if (file.createNewFile()){
                  System.out.println("File is created!");
                }else{
                  System.out.println("File already exists.");
                }
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write("ipconfig");
                bw.close();
                System.out.println("Done");

                Process p = Runtime.getRuntime().exec(file.getPath().toString());
                InputStream in = p.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                File op_file = new File("d:\\Result_file.txt");
                if (op_file.createNewFile()){
                  System.out.println("File is created!");
                }else{
                  System.out.println("File already exists.");
                }
                int c = -1;
                while((c = in.read()) != -1)
                {
                    baos.write(c);
                }
                String response = new String(baos.toByteArray());
                FileWriter fw1 = new FileWriter(op_file.getAbsoluteFile());
                BufferedWriter bw1 = new BufferedWriter(fw1);
                bw1.write(response);
                bw1.close();
                System.out.println("Done");
    }
 

}

No comments:

Post a Comment