Reading properties file

Asked

Viewed 691 times

0

How do I read data from a file properties on Android? Follows my code from onCreate:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    File file = new File(getPackageName()+ "/dados.properties");
    Properties pp = new Properties();
    FileInputStream fis = null;
    try {       
        fis = new FileInputStream(file);
        pp.load(fis);
        fis.close();
    } catch (Exception e) { }
}

There’s always a mistake in fis = new FileInputStream(file);.

  • 4

    Enter which error is occurring. It is probably due to the path to the file not being found. Search on how to get the application directory (where you probably want to save the properties file), for example here.

2 answers

1

I recommend putting the file dados.properties in the briefcase res/raw. By putting in this folder you can get one InputStream for any file in this folder with that code:

public InputStream readRaw(Context context, int rawResId) {
    return context.getResources().openRawResource(rawResId);
}

If you want more details check out the documentation of Resources.openRawResource(int id)

Fitting in your code would look like:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Properties pp = new Properties();

    try {
        pp.load(readRaw(this, R.raw.dados));
    } catch (Exception e) { }
}

0

The path you are looking for is not this one. Take a look at the function getFilesDir, it will return the path of your application files (/data/data/your package).

Try something like:

File file = new File(getFilesDir().getAbsolutePath() + "/dados.properties");

Browser other questions tagged

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