【问题标题】:Loading and saving a data file in android在android中加载和保存数据文件
【发布时间】:2013-01-11 02:44:27
【问题描述】:

我正在做一个简单的应用程序,它可以在 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();
        }
    }

    }

【问题讨论】:

  • 您的文件路径应采用以下格式.."/mnt/sdcard/yourfilename"
  • 不要指望“/mnt/sdcard”是正确的路径。使用 Environment.getExternalStorageDirectory()

标签: java android file load save


【解决方案1】:

虽然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.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多