我想要一个java文件的相对路径

我想要一个java文件的相对路径,java,Java,我是java新手。我想用java读取一个属性文件。但我的属性文件位于同一项目中的不同路径中 我不想硬编码。我想试试动态路径。 这是我的密码 Properties properties = new Properties(); try{ File file = new File("myFile.properties"); FileInputStream fileInput = new FileInputStream(file);

我是java新手。我想用java读取一个属性文件。但我的属性文件位于同一项目中的不同路径中

我不想硬编码。我想试试动态路径。 这是我的密码

     Properties properties = new Properties();
     try{
        File file = new File("myFile.properties");
        FileInputStream fileInput = new FileInputStream(file);

        properties.load(fileInput);

     }catch(Exception ex)
     {
         System.err.println(ex.getMessage());
     }
我的文件位于文件夹
webapp/txt/myFile.properties


有人能帮我解决这个问题吗?

如果它位于
webapp/txt.myFile.properties
下,并且webapp是公共web空间,那么您需要使用绝对URL来阅读它

getServletContext().getRealpath("/txt/myFile.properties")
Properties prop=新属性();
InputStream输入=getServletContext().getResourceAsStream(“/txt/myFile.properties”);
道具载荷(输入);
System.out.println(prop.getProperty());

解决此问题的一种方法是将文件的绝对路径分为两部分

  • 直到项目文件夹的路径
  • 从项目文件夹开始的路径(相对路径)
  • 您可以在应用程序中处理这两个属性,然后连接并获得文件的绝对路径。相对路径仍然是可配置的

    public Properties loadDBProperties() {
        InputStream dbPropInputStream = null;
        dbPropInputStream = DbConnection.class
                .getResourceAsStream("MyFile.properties");
        dbProperties = new Properties();
        try {
            dbProperties.load(dbPropInputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return dbProperties;
    }
    
    您可以从中调用此方法

    dbProperties = loadDBProperties();
    String dbName = dbProperties.getProperty("db.schema");//you can read your line form here of properties file
    

    就我所记得的,当这样编码时,它通常会在带有WAR或JAR的文件夹中查找属性文件。
    dbProperties = loadDBProperties();
    String dbName = dbProperties.getProperty("db.schema");//you can read your line form here of properties file