当我尝试在 java 中读取控制台输出错误时没有得到结果
Don't get result when I try to read console output error in java
我正在使用 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()
块中提及。 (如果有多个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
}
这样,您就不再需要您提供的完全错误的代码了。你可以删除它
我正在使用 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()
块中提及。 (如果有多个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
}
这样,您就不再需要您提供的完全错误的代码了。你可以删除它