非常纠结的查找错误的过程。

来源:互联网 发布:java run 编辑:程序博客网 时间:2024/06/05 07:32

刚刚写了一个Dao类,用来完成对一个xml文件的读写操作。

可是在测试的时候,发现一个错误,这个错误叫做NullPointException.


但是在几次修改之后,我发现测试通过,但是在console下又输出上面的错误。可能是刚学JAVA的原因,我急着想知道自己测试的结果。于是就去寻找对应的XML文件,发现XML文件并没有完成我需要的add操作。


我又纠结了。

于是我又去运行,最后将代码定位到

Document document = reader.read(new File(filepath));


这行。

我当时觉得问题可能是出在filepath是无效路径上,(我丝毫没想到,如果filepath是无效的路径,那么抛出的异常会是不相同的异常。

于是,我不知道如何确定是不是这个filepath的问题。

开始,我想通过创建一个文件输入流,然后将filepath对应的文件的文件内容输出到控制台。

创建之后,又告诉我是如上的NullPointException异常。


我开始看这个函数的提示,有如下的信息,英语很差的我,也勉强能够看懂这上面的内容。


Creates a file output stream to write to the file with the specified name. A newFileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkWrite method is called withname as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then aFileNotFoundException is thrown.

Parameters:
name the system-dependent filename
Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
SecurityException - if a security manager exists and itscheckWrite method denies write access to the file.
See Also:
java.lang.SecurityManager.checkWrite(java.lang.String)


这里其实可以得到一条信息,如果对应的路径没有对应的文件,虚拟机会自动创建一个文件,而不会出现问题。

但是这个时候,我依旧执迷不悟,我一直都认为错误是在路径出现了错误。

这种认定了就难以改正的思路必须要改正,狠狠的改正。



最后,我发现我的路径名是通过如下的方式获取的。

filepath = XmlUtils.class.getClassLoader().getResource("user.xml").getPath();
//        filepath = "D://java/userloginApp/src/user.xml";


于是,我自己直接使用System.out.println(filepath);

然后进行测试,发现输出的值为null;


这个时候,我明白了引发问题的原因,但是依旧不知道为什么是null;

于是,我就通过加上filepath = "D://java/userloginApp/src/user.xml";

这条语句进行测试,发现结果依然是空。


显然,这条语句没有被执行。

于是,我终于发现了一个重大的问题。

static
    {
        filepath = XmlUtils.class.getClassLoader().getResource("user.xml").getPath();
//        filepath = "D://java/userloginApp/src/user.xml";
    }


 我忘记了加static这个关键字,所以,这两条语句都不会执行。。。

我一下子晕了。


从头到尾,这里花费我的时间将近一个小时。结果找到的问题确实如此一个错误。这实在让人心痛。


总结两点吧:

1,检查的时候,一定要注意是什么异常,可能会因为什么情况发生。

2,你想到的不一定是对的,要随时准备放弃自己的想法,不要苦苦的坚持。