我想知道如何在.apk安装期间在内部存储中创建文件。
我的问题是,当我使用MainActivity的onCreate方法放置文件时,每次重新启动应用程序时,我的文件内容都会被删除。
我也试过使用file.exists但它没有用。
以下是我正在使用的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Internal internal = new Internal();
String file_name = "profil1.txt";
String file_name1 = "profil2.txt";
File f = new File(file_name);
try {
if(f.exists()){
Log.d(TAG, "les fichiers sont deja cree");
}else {
FileOutputStream fos = openFileOutput(file_name, Context.MODE_WORLD_WRITEABLE);
FileOutputStream fos1 = openFileOutput(file_name1, Context.MODE_WORLD_WRITEABLE);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file =getFilesDir();
Log.d("TAG", file.getAbsolutePath());
Path = file.getAbsolutePath();
//internal.setFile();
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
setContentView(R.layout.main_grid);
mGrid = (GridView) findViewById(R.id.gridview);
mGrid.setColumnWidth(95);
mGrid.setVisibility(0x00000000);
// content.dispatchSystemUiVisibilityChanged(BIND_ADJUST_WITH_ACTIVITY);
registerIntentReceivers();
// requestWindowFeature(Window.FEATURE_NO_TITLE);
appManager = new ApplicationManager(this, getPackageManager());
appManager.loadApplications(true);
bindApplications();
bindButtons();
// Try to find activity to auto-start on create.
int i = 0;
while (i < APPLICATION_START_NAMES.length) {
Intent startIntent = appManager
.getIntentByName(APPLICATION_START_NAMES[i]);
if (startIntent != null) {
// Found it, let's start and continue.
startActivity(startIntent);
break;
}
i++;
Log.d("TAG", "application number" + i);
// we will try to hid the stat bar temporory because to hid it w e
// neeed root acces
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
// Administrat.SINGLETON.init(this);
}
答案 0 :(得分:1)
您无法在安装期间执行代码。您在onCreate()
中获得的代码几乎是正确的。问题是当你检查文件的存在时,你还没有说要在哪里寻找它。您需要指定应用程序的私有目录。试试这个:
String file_name = "profil1.txt";
String file_name1 = "profil2.txt";
File f = new File(getFilesDir(), file_name); // File in the private directory
try {
if(f.exists()){
...
}
}