【问题标题】:Libgdx:Save and getback files in androidLibgdx:在android中保存和取回文件
【发布时间】:2014-08-15 10:16:13
【问题描述】:

我有一个文本作为字符串,我必须将它保存在一个新的或已经创建的文件夹中,并带有我自己的文件扩展名。用户还应该能够复制和使用这些文件。我已经浏览了许多教程,但大多数都令人困惑。libgdxandroid平台)有没有简单的方法来将字符串保存为具有我自己的扩展名的文件,并从内存中的文件列表中取回。 我需要的是:

  1. 将文件保存到新文件夹或现有文件夹(用户可用)的函数。将字符串作为参数。
  2. 获取指定文件夹中“.my”文件列表的另一个函数。

【问题讨论】:

  • steigert 有一个很好的tutorial 关于文件。希望有帮助
  • 您是否只想将数据保存在文件中以供以后访问,例如保存高分? SharedPreferences 是一种简单的方法,无需任何麻烦
  • 我很确定他正在寻找files,因为他也需要复制它们。您不能只是复制共享偏好,并且只存储键值对。

标签: java android libgdx


【解决方案1】:

保存:

    public boolean saveToFile(String fileName)
    {
        FileHandle fileHandle = Gdx.files.local(fileName + ".txt");
        BufferedWriter bw = new BufferedWriter(fileHandle.writer(false));
        try
        {
            bw.append("stuff");

        }
        catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }
        finally
        {
            try
            {
                bw.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return true;
    }

并阅读:

        FileHandle f = Gdx.files.local(fileName + ".txt");
        BufferedReader r = null;
        try
        {
            r = new BufferedReader(f.reader());
            String line = null;
            while((line = r.readLine()) != null)
            {
                //read the lines
            }
        }
        catch (GdxRuntimeException e)
        {
            //file does not exist yet
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (r != null)
            {
                try
                {
                    r.close();
                }
                catch (IOException e)
                {
                }
            }
        }

【讨论】:

  • 虽然从技术上讲,如果用户需要能够复制文件,那么使用external 而不是local 可能会更好。
猜你喜欢
  • 2016-09-11
  • 1970-01-01
  • 2014-05-11
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多