Java 在android中加载和保存数据文件
我正在做一个用java加载和保存文件的简单应用程序。我正在尝试将它移植到Android上,但在让它查看文件时遇到了麻烦 我当前使用的文件路径为Java 在android中加载和保存数据文件,java,android,file,load,save,Java,Android,File,Load,Save,我正在做一个用java加载和保存文件的简单应用程序。我正在尝试将它移植到Android上,但在让它查看文件时遇到了麻烦 我当前使用的文件路径为 private static final String SAVE_FILE_PATH = "data/save"; 以下是从文件加载数据的函数: public void loadData() throws FileNotFoundException { File file = new File(SAVE_FILE_PATH); Sca
private static final String SAVE_FILE_PATH = "data/save";
以下是从文件加载数据的函数:
public void loadData() throws FileNotFoundException {
File file = new File(SAVE_FILE_PATH);
Scanner scanner;
if (file.exists()) {
scanner = new Scanner(new FileInputStream(file));
try {
while (scanner.hasNextLine()) {
allPlayers.add(new Player(scanner.nextLine()));
}
} finally {
scanner.close();
}
}
else {
System.out.println("No file found");
}
} finally {
scanner.close();
}
}
}
<> > <代码> GutExalStRealDirectory()/Case>获取SD卡的路径,考虑使用<代码> Actudio.FuturalFielsDE()/<代码>,它将返回(并创建必要时)一个对您的应用程序名义上是私有的目录。它还有一个优点,即如果卸载应用程序,它将自动删除。这在API8中是新的,所以如果您支持较旧的设备,您可能不想使用它 否则,您将不得不遵循ρѕρєK的建议。不要忘记创建要使用的存储目录。我的代码通常如下所示:
/**
* Utility: Return the storage directory. Create it if necessary.
*/
public static File dataDir()
{
File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory() ) {
// TODO: warning popup
Log.w(TAG, "Storage card not found " + sdcard);
return null;
}
File datadir = new File(sdcard, "MyApplication");
if( !confirmDir(datadir) ) {
// TODO: warning popup
Log.w(TAG, "Unable to create " + datadir);
return null;
}
return datadir;
}
/**
* Create dir if necessary, return true on success
*/
public static final boolean confirmDir(File dir) {
if( dir.isDirectory() ) return true;
if( dir.exists() ) return false;
return dir.mkdirs();
}
现在使用此选项指定保存文件:
File file = new File(dataDir(), "save");
Scanner scanner;
if (file.exists()) {
// etc.
}
您的文件路径应为以下格式:“/mnt/sdcard/yourfilename”不要指望“/mnt/sdcard”是正确的路径。使用Environment.getExternalStorageDirectory()