harili
harili

Reputation: 477

Thread.currentThread().getContextClassLoader().getResourceAsStream(); return null

I have a problem with my current fonction :

public static Connection ConnectDB(){
        try{
        File fichier = new File("\\XFiles\\Conf\\init.xml");
        System.out.println(fichier.getAbsoluteFile());
        String nom = fichier.getName();
        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(nom);
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(input));
        XPath xpath = XPathFactory.newInstance().newXPath();

        String url = (String) xpath.compile("//init//jdbc//url").evaluate(document, XPathConstants.STRING);
        String driver = (String) xpath.compile("//init//jdbc//driver").evaluate(document, XPathConstants.STRING);
        String username = (String) xpath.compile("//init//jdbc//username").evaluate(document, XPathConstants.STRING);
        String password = (String) xpath.compile("//init//jdbc//password").evaluate(document, XPathConstants.STRING);   

        String passwordCryp = String.valueOf(password);

        Cryptage cipherUtil = new Cryptage();
        String mdpCrypte = cipherUtil.encrypt(passwordCryp);

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //méthode qui retourne la classe de l'objet assoccié au string
        if(conn==null){ //si la connexion est null
            conn = DriverManager.getConnection(url+"integratedSecurity=true;",username,password); //récupérer les informations de la connexion (serveur, BDD...)
            logger.debug("Connexion Réussite");
        }

        return conn; //retourne la connexion
        }catch(Exception e){ //s'il y a une erreur
            logger.error(e);
            return null;
        }
    }

When I compile and run it, the variable 'input' is always null. I've tried to put the xml file in a File object, but it still doesn't work.

Upvotes: 0

Views: 557

Answers (1)

ultimate
ultimate

Reputation: 723

String nom = fichier.getName(); will only return the filename, which is init.xml. If you want to access the file in the path you specified you should use fichier.getPath() or even fichier.getAbsolutePath()

Upvotes: 1

Related Questions