-1

I'm using NetBeans to build a java project, I try to read every error shown in the console and put it in frame to be shown to user. I searching for a way to do that I found Console c=System.console() to take every output written in console so I try first to test this command by read errors and put them in a file

  if(c.readLine().equals("")){
        System.out.println("OK!!!");
    }else{
         System.out.println("not OK!!!");
        try {
         FileWriter myWriter = new FileWriter("Error.txt");
         myWriter.write(""+c.readLine().toString());
         myWriter.close();
         System.out.println("Successfully wrote to the file.");
      } catch (IOException e) {
         System.out.println("An error occurred.");
         e.printStackTrace();
       }
    }

But I get this error exceptionException in thread "AWT-EventQueue-0" java.lang.NullPointerException

And this error exception still even after I put System.out.println("Something here");in main project to see if this exception shown because I don't put nothing in console but gone when I scanner something in console, but this is not what I looking for so how can I read error from console?

1 Answers1

1

if you want to write the output of an Exception into a file, you have to mention that in the catch() block. (if you have multiple catch blocks, you can create a method that contains the writing process and call it each time, to avoid repeating the same code each time )

try
{
   //... some code...
}
catch (Exception e)
{
     FileWriter myWriter = new FileWriter("Error.txt",true);
     PrintWriter pw = new PrintWriter (myWriter);
     e.printStackTrace (pw);
     System.out.println("Successfully wrote to the file."); //this will be only shown in the console,
                                                           // but never printed in the file
}

this way, you no longer need the code that you provided which is totally wrong. you can just remove it

Bashir
  • 2,057
  • 5
  • 19
  • 44