Problem reading property file

Asked

Viewed 683 times

0

I created a propertie file for the database to read this file from there but the console presents me the following error:

Erronull\properties\conexao.propertie (O sistema não pode encontrar o caminho especificado)
Erronull\properties\conexao.propertie (O sistema não pode encontrar o caminho especificado)
Erronull\properties\conexao.propertie (O sistema não pode encontrar o caminho especificado)
ConexaoMySQL: The url cannot be null
java.sql.SQLException: The url cannot be null
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at modelo.ConexaoMySQL.conectar(ConexaoMySQL.java:18)
    at helper.BancoDadosHelper.getNomeColunas(BancoDadosHelper.java:18)
    at principal.Main.testaConexDB(Main.java:38)
    at principal.Main.menu(Main.java:30)
    at principal.Main.main(Main.java:17)
Exception in thread "main" java.lang.NullPointerException
    at helper.BancoDadosHelper.getNomeColunas(BancoDadosHelper.java:21)
    at principal.Main.testaConexDB(Main.java:38)
    at principal.Main.menu(Main.java:30)
    at principal.Main.main(Main.java:17)

Related Classmysql:

package modelo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConexaoMySQL {

    private static Connection conexao;

    public static boolean conectar() {
        Propriedade.setPath(System.getProperty("jdbc.url")+"\\properties\\conexao.propertie");
        String url = Propriedade.getValor("url");
        String usr = Propriedade.getValor("user");
        String pwd = Propriedade.getValor("password");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conexao = DriverManager.getConnection(url,usr,pwd);
            System.out.println("ConexaoMySQL.conectar");
            return true;
        } catch (Exception e) {
            System.out.println("ConexaoMySQL: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public static void fecharConexao() {
        if (conexao != null) {
            try {
                conexao.close();
                conexao = null;
                System.out.println("ConexaoMySQL.fecharConexao");
            } catch (SQLException e) {
                System.out.println("ConexaoMySQL: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public static Connection getConexao(){
        return conexao;
    }

}

Property class :

package modelo;

import java.io.FileInputStream;
import java.util.Properties;

public class Propriedade {

    private static String path;

    public static void setPath(String caminhoDoArquivo) {
        path = caminhoDoArquivo;
    }

    public static String getValor(String key) {
        String returning = null;
        FileInputStream fis = null;
        Properties prop = new Properties();
        try {
            fis = new FileInputStream(path);
            prop.load(fis);
            returning = prop.getProperty(key);
            if (fis != null) {
                fis.close();
            }
        } catch (Exception e) {
            System.out.println("Erro" + e.getMessage());
        }
        return returning;
    }

}

File connected.propertie.:

url = jdbc:mysql://localhost:3306/sistema;
user = root;
password = ;

1 answer

1


Both your property file and the code that retrieves it are wrong, being the root of the error due to the fact that the file is not found.

The error presented is:

System cannot find specified path

See that you’re recovering (System.getProperty("jdbc.url")) a system property that is currently non-existent, to form the path and is returning null being the final generated path equal to null\properties\conexao.propertie

For this, consider recovering the file from properties as a Resource stream, case he’s in the classpath of its application, something like this:

InputStream fis = Propriedade.class.getResourceAsStream("/properties/conexao.propertie")

This makes it unnecessary setPath class Propriedade. Another observation is that you can load the properties file only once, in a static block even.

So in the end, the class Propriedade would look like this:

public final class Propriedade {

    private Propriedade() {}

    private static final Properties prop = new Properties();

    static {
        try (final InputStream fis = Propriedade.class.getResourceAsStream("/properties/conexao.propertie")) {
            prop.load(fis);
        } catch (final IOException e) {
            throw new ExceptionInInitializerError(e.getMessage());
        }
    }

    public static String getValor(final String key) {
        final String returning = prop.getProperty(key);
        return returning != null ? returning : key;
    }

}

Finally, considering the contents of your property file:

url = jdbc:mysql://localhost:3306/sistema;
user = root;
password = ;

This will always return the ; which, in the case of user and password, will probably generate error.

If possible, prefer this content:

url = jdbc:mysql://localhost:3306/sistema
user = root
password = 

To use it is the same way you were doing before, Propriedade.getValor("propriedade"), but in conectar of ConexaoMySQL you should remove the first line of the method.

One example recovering is this:

System.out.println("Propriedade 'user' (valor=root;): " + Propriedade.getValor("user"));
System.out.println("Propriedade 'key' (inexistente): " + Propriedade.getValor("key"));

That generates this result:

Propriedade 'user' (valor=root;): root;
Propriedade 'key' (inexistente): key
  • In the method connect I remove this stretch then ? (Property.setPath(System.getProperty("user.dir")+" related properties.propertie"); ), but still giving error.

  • @Jarwin this, removes it and uses the class this way. The file is in the classpath of your application, isn’t it? Another thing: removed the ; of property?

  • Face is kind of hard to explain the error that is happening, here is my complete code for you to better understand my situation: https://www.dropbox.com/s/0vo699f7b4nz1v9/AulaBanco.zip?dl=0 and my sql file: http://pastebin.com/LxfWA3GG

  • @Jarwin guy, put the error, unfortunately I can’t take your project and test here, I just won’t install Mysql for this or convert SQL to run in another database. This answer solves your initial error, if it is another completely different error, consider creating another answer.

  • 'Exception in thread "main" java.lang.Exceptionininitializererror at model.ConexaoMySQL.connect(Conexaomysql.java:13) at helper.BancoDadosHelper.getNomeColunas(Bancodadoshelper.java:18) at principal.Main.testaConexDB(Main.java:38) at principal.Main.menu(Main.java:30) at principal.Main.main(Main.java:17) Caused by: java.lang.Nullpointerexception at java.util.Properties$Linereader.readline(Unknown Source) at java.util.Properties.load0(Unknown Source) at java.util.Properties.load(Unknown Source) at modelo.Propriedade. <clinit>(property.java:15) ... 5 more'

  • @Jarwin your property file is not on classpath application, just as it is not in a folder called properties who is in the classpath. Put up the file conexao.propertie in the briefcase src and alters of /properties/conexao.propertie for /conexao.propertie

  • You have now given this error: Conexaomysql: Access denied for user 'root'@'localhost' (using password: YES) java.sql.Sqlexception: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)&#xA; at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3835)&#xA; at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3771)&#xA; at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:870)&#xA; at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(Mysqlio.java:1659) .......... And I don’t have a password in my bank...

  • @Jarwin man, are you reading the error messages? Did you see that the problem is authentication? Take a look, make the necessary changes, the best way to learn is to explore the problems and not just expect someone to do their expensive homework if you look at the getValor of Propriedade will see why the error, is simple, anyway the answer is updated...

  • It worked out dude, sorry to keep insisting on mistakes all the time is that I until I can’t figure out what’s going on I go crazy !!!! I just wanted to understand why returning.length() > 0 ?

  • @Jarwin this why I’ll leave it up to you to find out, run tests and everything, you’ll see why he made a difference in your case :)

  • Ok , You recommend me some good book to learn java web and JDBC in view of your experience ?

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.