在android中加载和保存数据文件

时间:2013-01-11 02:44:27

标签: 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);

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

    }

1 个答案:

答案 0 :(得分:2)

虽然getExternalStorageDirectory()为您提供了SD卡的路径,但请考虑使用Activity.getExternalFilesDir(),它将返回(并在必​​要时创建)名义上专用于您的应用程序的目录。它还具有以下优点:如果卸载了应用程序,它将自动删除。这是API 8中的新功能,因此如果您支持旧设备,则可能不想使用它。

否则,你必须遵循ρяσѕρєя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.
}