Apache Tomcat应用程序中的相对文件路径引用[重复]

问题描述 投票:-2回答:1

我目前正在开发一个Web应用程序,我有一个名为File.xml的XML文件,其中包含PostgreSQL连接参数:login,password,ip_address,pilote,port,bdd。 。我将此文件添加到Apache Tomcat的bin文件夹中。我有class.jav,它使用XML文件的参数连接到数据库。

当我运行该类时,我得到了else行的结果(找不到文件)。我怀疑该类没有访问apache bin文件夹下的File.xml。该怎么办?

    private ParamBDD()
{
    SAXBuilder sxb = new SAXBuilder();
    try
    {
        mes_documents mes=new mes_documents();
        Fichier fichier = new Fichier();
        File file=new File("File.xml");
        //File file=new File(this.getClass().getResource("/resources/Fichiers_parametres/parametreconnexion_crypte.xml").getFile());



            String str_fichier ="File.xml";


            if (file.isFile())
            {
                org.jdom.Document document = sxb.build(new File(str_fichier));

                Element racine = document.getRootElement();
                List listParam = racine.getChildren("param");

                Iterator i = listParam.iterator();
                while (i.hasNext())
                {
                    Element courant = (Element) i.next();

                    pilote = courant.getChild("pilote").getText().trim();
                    utilisateur = courant.getChild("login").getText().trim();
                    password = courant.getChild("password").getText().trim();
                    adresseIP = courant.getChild("adresseIP").getText().trim();
                    port = courant.getChild("port").getText().trim();
                    BDDGenerale = courant.getChild("bdd").getText().trim();
                    System.out.println("BDD Generale:"+BDDGenerale);

                    //JOptionPane.showMessageDialog(null, "Fin du fichier","",JOptionPane.INFORMATION_MESSAGE);
                }

            }
            else JOptionPane.showMessageDialog(null, "le fichier contenant les parametres n'existe pas","",JOptionPane.INFORMATION_MESSAGE);

    }
java tomcat java-ee
1个回答
2
投票

Java中的所有相对文件路径都是相对于用户启动Java程序时所在的目录进行解析的。启动程序时所在的目录记录在系统属性中:System.getProperty("user.dir");

所以,如果你是,例如,当你启动tomcat时在/home/asma/myproject,那么user.dir文件夹将是/home/asma/myproject

然后,当你有一个文件引用,如:

File file = new File("File.xml");

然后Java系统将查找文件/home/asma/myproject/File.xml

您需要做的是将文件引用设置为绝对路径,或者确保在实际启动tomcat时位于bin文件夹中...(这是一种痛苦......所以不要这样做)。

将您的代码更改为:

File file = new File(System.getProperty("catalina.base") + "/bin/File.xml");
© www.soinside.com 2019 - 2024. All rights reserved.