user940371
user940371

Reputation: 35

i want relative path for a file in java

I am new to java. I want to read a properties file in java. But i have my properties file in a different path in the same project.

I don't want to hard-code it. I want try with dynamic path. Here is my code,

     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());
     }

my file is in the folder, webapp/txt/myFile.properties.

Can any one help me in solving this issue?.

Upvotes: 0

Views: 2335

Answers (4)

amicngh
amicngh

Reputation: 7899

  Properties prop=new Properties();
  InputStream input = getServletContext().getResourceAsStream("/txt/myFile.properties");
  prop.load(input);
  System.out.println(prop.getProperty(<PROPERTY>));

Upvotes: 0

Dinup Kandel
Dinup Kandel

Reputation: 2505

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;
}

you can call this method from

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

Upvotes: 1

Santosh
Santosh

Reputation: 17923

One way to solve this is split the absolute path to you file in two parts

  1. Path till your project folder
  2. path from you project folder onwards (Relative path)

You can tread these two properties in your application and concatenate and get the absolute path of the file. The relative path remains configurable.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240946

if its under webapp/txt.myFile.properties and webapp is the public web space, then you need to read it using absolute URL

getServletContext().getRealpath("/txt/myFile.properties")

Upvotes: 0

Related Questions