-1

With the code below, I'm trying to simulate the command shell, I even created a command and called it (Showerrlog) to help the user seeing his invalid commands that he entered during his current work session, as you can see, I did that using filehandler, which will save the wrong commands in a log file. But as you know filehandler will start a new file for each new working session, and the new file will be named as (file.log, file.log.1, file.log.2, etc) and so on, the question is: how to make the program to avoid opening a new file everytime, in other words isn't there any other way that the program will just format the previous work session and add the new one instead?

Or at least how to make the program open the last log file which belongs to the current work session ?

public class WithEyul implements Runnable {

    String command;

    public WithEyul(String command) {
        this.command = command;
    }

    @Override    
    public void run() {
        List<String> input = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(command);
        while (tokenizer.hasMoreTokens()) {
            input.add(tokenizer.nextToken());
        }
        ProcessBuilder pb = new ProcessBuilder(input);
        // ProcessBuilder creates a process corresponding to the input command
        // now start the process
        BufferedReader br = null;
        try {
            Process proc = pb.start();
            // obtain the input and output streams
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            // read what the process returned
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (java.io.IOException ioe) {

            try {
                System.err.println("Error");

                Logger logger = Logger.getLogger("Testing");
                FileHandler fh = new FileHandler("E:/MyLogFile.log");

                logger.addHandler(fh);
                SimpleFormatter formatter = new SimpleFormatter();
                fh.setFormatter(formatter);
                logger.info(command);
            } catch (SecurityException e) {
                printStackTrace();
            } catch (IOException ex) {
                Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
                }
            }    
        }    
    }    
}

and here is the main method class

public class TestProcessBuilder {

    static void createProcess(String command) throws java.io.IOException {
        Thread t = new Thread(new WithEyul(command));
        t.start();    
    }

    public static void main(String[] args) throws java.io.IOException {

        String commandLine;
        File wd;
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("\n\n***** Welcome to the Java Command Shell *****");
        System.out.println("If you want to exit the shell, type END and press RETURN.\n");
        // we break out with ‘END’
        while (true) {
            // show the Java shell prompt and read what command they entered
            System.out.print("jsh>");
            commandLine = console.readLine();
            // if user entered a return, just loop again
            if (commandLine.equals("")) {
                continue;
            }
            if (commandLine.equalsIgnoreCase("Showerrlog")) {
                try {

                    // Runtime.getRuntime().exec("E:\\MyLogFile.log");
                    if (Desktop.isDesktopSupported()) {
                        Desktop.getDesktop().open(new File("E:\\MyLogFile.log"));
                    }

                } catch (IOException ex) {
                    Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (commandLine.toLowerCase().equals("end")) { //User wants to end shell
                System.out.println("\n***** Command Shell Terminated. See you next time. BYE for now. *****\n");
                System.exit(0);
            }

            createProcess(commandLine);

        }
    }
}
Anton Savin
  • 40,838
  • 8
  • 54
  • 90

1 Answers1

0

You could use the FileHandler constructor that allows you to specify the rotation, limit, and append options.

new FileHandler("E:/MyLogFile.log", 0, 1, true);

The FileHandler can rotate for a number of reasons that are out of your control. If you don't want to deal with file rotation you could open a FileOutputStream and wrap that with a StreamHandler. However, you will have to handle file locking conflicts.

You should also avoid creating and adding a handler that points to the same target file everytime an error is generated. You should install the handler on startup and store a string reference to your logger.

jmehrens
  • 10,580
  • 1
  • 38
  • 47