Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用外部文件时出现空指针异常_Java_Mysql_File_Path_Nullpointerexception - Fatal编程技术网

Java 使用外部文件时出现空指针异常

Java 使用外部文件时出现空指针异常,java,mysql,file,path,nullpointerexception,Java,Mysql,File,Path,Nullpointerexception,当我尝试使用另一个文件来执行脚本文件以查找脚本时,会出现NullPointerException 下面是用于使用DB.conf文件执行到MySql DB的连接的代码。如果数据库不存在,则使用DB.conf文件,代码应该提取脚本的路径。脚本的路径与DB.conf的路径相同 这是我的密码: public class MySqlConnection { /** * campo per la connessione al database */ protected Connection conne

当我尝试使用另一个文件来执行脚本文件以查找脚本时,会出现NullPointerException

下面是用于使用DB.conf文件执行到MySql DB的连接的代码。如果数据库不存在,则使用DB.conf文件,代码应该提取脚本的路径。脚本的路径与DB.conf的路径相同

这是我的密码:

public class MySqlConnection {

/**
 * campo per la connessione al database
 */
protected Connection connessione;

/**
 * campo statement
 */
protected Statement stat;

/**
 * campo per i risultati della query
 */
  protected ResultSet res;

    /**
 * campo di preparazione statement
 */
   protected PreparedStatement prepStat;

   protected boolean connect() throws ClassNotFoundException, SQLException,
        IOException {
    connessione = null;
    boolean connection = false;


    InputStream input = getClass().getResourceAsStream("/DB.conf");
    BufferedReader br = new BufferedReader(new InputStreamReader(input));
    new Driver();
    String src = br.readLine().toString();
    String db = br.readLine().toString();
    String user = br.readLine().toString();
    String password = br.readLine().toString();

    try {
        String jdbc = (new StringBuilder("jdbc:mysql://")).append(src)
                .append("/").append(db).toString();
        connessione = DriverManager.getConnection(jdbc, user, password);

    } catch (SQLException e) {
        if (e.getErrorCode() == 1049) {
            JOptionPane
                    .showMessageDialog(null,
                            "Database 'Carloan' non esistente! \nInstallazione del db in corso...");
            String jdbc = (new StringBuilder("jdbc:mysql://")).append(src)
                    .toString();
            connessione = DriverManager.getConnection(jdbc, user, password);
            //HERE I EXTRACT THE PATH OF THE SCRIPT FROM THE FILE DB.CONF
            //AND THAN I GET THE NULLPOINTER
            String sqlScriptPath = br.readLine().toString();
            InputStream input2 = getClass().getResourceAsStream(sqlScriptPath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(input2));
            ScriptRunner sr = new ScriptRunner(connessione, false, false);
            sr.runScript(reader);

            JOptionPane
                    .showMessageDialog(null, "Installazione completata!");
        } else {
            if (e.getErrorCode() == 1045) {
                JOptionPane
                        .showMessageDialog(
                                null,
                                "Username o password del DB errati! \n Controllare il file di configurazione e riprovare.");
            } else {
                JOptionPane
                        .showMessageDialog(
                                null,
                                "Errore nella connessione al database! \n       Contattare l'amministratore di sistema.\nIl sistema verrà chiuso ora.");
            }
        }
    }
    br.close();
    input.close();
    connection = true;
    return connection;
  }

 protected boolean close() throws SQLException {
    boolean chiuso = false;
    connessione.close();
    chiuso = true;
    return chiuso;
}

}
这是DB.conf文件的内容

localhost:3306
CarLoan
root
root
CarLoan.sql
这是空指针的堆栈跟踪:

java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at integration_tier.OggettiDAO.MySqlConnection.connect(MySqlConnection.java:70)
at integration_tier.OggettiDAO.CategoriaDAO.create(CategoriaDAO.java:28)
at business_tier.ApplicationService.add(ApplicationService.java:21)
at presentation_tier.ApplicationController.handleRequest(ApplicationController.java:41)
at presentation_tier.FrontController.handleRequest(FrontController.java:29)
at presentation_tier.GuiController.ControllerSchermataImpiegato.catdao(ControllerSchermataImpiegato.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$ClickGenerator.postProcess(Unknown Source)
at javafx.scene.Scene$ClickGenerator.access$8100(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(Unknown Source)
at java.lang.Thread.run(Unknown Source)

根据堆栈跟踪,MySqlConnection.java的第70行出现异常。据你说,这条线是

BufferedReader reader = new BufferedReader(new InputStreamReader(input2));
对getClass.getResourceAsStreamsqlScriptPath的调用;正在返回null值,将InputStream input2设置为null。不能使用空变量input2创建新的InputStreamReaderinput2

根据文件DB.conf,sqlScriptPath的值是CarLoan.sql。考虑到您对getClass.getResourceAsStream/DB.conf的调用;如果成功,则DB.conf中sqlScriptPath的值可能应该是/CarLoan.sql

确认sqlScriptPath的值设置为/CarLoan.sql,并且正在从getClass.getResourceAsStreamsqlScriptPath检索为NOTNULL

确认文件(显式命名为CarLoan.sql,大小写相同)与DB.conf位于同一文件夹中,并且具有与DB.conf文件相同的安全访问权限


另外,确保所有IO.close调用都在finally子句中完成。

根据堆栈跟踪,MySqlConnection.java的第70行出现异常。由于我们看不到行号,第70行的代码是什么?代码是:BufferedReader reader=new BufferedReadernew InputStreamReaderinput2@是的,我用/CarLoan.sql修改了sqlScriptPath的值,但它给了我NullPointerException。是的,getClass.getResourceAsStreamsqlScriptPath;返回NullCarloan.sql是否存在?它与DB.conf在同一个文件夹中吗?是的,这些文件在同一个文件夹中。它们从一开始就在同一个文件夹中,还是您只是将它们放在一起?如果你只是把它们放在一起,你需要回收容器,然后再试一次。它的大小写是否相同?CarLoan.sql上的权限与DB.conf上的权限相同吗?