我正在使用NetBeans
来构建Java项目,我尝试读取控制台中显示的每个错误并将其放在框架中以显示给用户。我正在寻找一种方法来发现Console c=System.console()
接受控制台中写入的每个输出,因此我首先尝试通过读取错误来测试此命令并将其放入文件中
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();
}
}
但是我收到此错误异常Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
而且即使在我将System.out.println("Something here");
放在主项目中后仍然看到此错误异常,以查看是否显示此异常,因为我没有在控制台中放任何东西,而是在控制台中扫描某些内容时消失了,但这不是我想要的如何从控制台读取错误?
[如果要将Exception
的输出写入文件,则必须在每个catch()
块中都提及。
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
}
这样,您不再需要提供的代码。您可以将其删除