在我当前的应用程序中,我需要维护一个config.properties
文件,并且需要从该属性文件中获取Java文件中的数据。我将属性文件和ConfigUtil.java
放置在其中,访问这些属性文件的值位于同一位置。但是,当我运行该应用程序时,它会给出FileNotFoundException
。
我无法弄清为什么当两个文件都位于同一文件夹中时为什么不加载属性文件。
我的ConfigUtils.java代码是:
public class ConfigUtil {
private Properties properties;
InputStream inputStream = null;
public Properties getUrl(){
properties = new Properties();
try {
inputStream = new FileInputStream("config.properties");
properties.load(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return properties;
}
}
和config.properties文件也位于同一文件夹中
config.properties
的位置是:ConfigUtil.java
的位置是:最佳答案
步骤1
在 Assets 文件夹中创建一个.properties文件,如果您没有 Assets 文件夹,请在主文件夹下创建一个
config.properties
name=User Name
age=User Age
ok=Click
步骤2
创建一个Util.java文件以读取属性文件。
Util.java
package javaant.com.propertiesfile;
import android.content.Context;
import android.content.res.AssetManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by Nirmal Dhara on 12-07-2015.
*/
public class Util {
public static String getProperty(String key,Context context) throws IOException {
Properties properties = new Properties();;
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open("config.properties");
properties.load(inputStream);
return properties.getProperty(key);
}
}
步骤3
通过调用Util.getProperty(,getApplicationContext())在属性文件中使用变量。
MainActivity.java
package javaant.com.propertiesfile;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// read value from properties file
TextView txtname= (TextView) findViewById(R.id.txtname);
TextView txtage= (TextView) findViewById(R.id.txtage);
Button btnok= (Button) findViewById(R.id.btnok);
try {
txtname.setText(Util.getProperty("name",getApplicationContext()));
txtage.setText(Util.getProperty("age",getApplicationContext()));
btnok.setText(Util.getProperty("ok",getApplicationContext()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
请从此处下载完整代码http://javaant.com/how-to-use-properties-file-in-android/#.VwzippN96Hs